PDA

View Full Version : Read binary file


jaca
11th January 2008, 00:22
Hi,
I am with problem in the reading of a binary file.
I made thus:

#include <QApplication>
#include <QDataStream>
#include <QFile>
#include <QVector>

#include <iostream>
using namespace std;

int main(int argc, char *argv[]) {

QApplication app(argc, argv);

QFile file("wavemin_501ns.ad");
file.open(QIODevice::ReadOnly);
QDataStream in(&file);

qint64 tam = file.size();
qint64 ns = tam/sizeof(float);
QVector<float> vet(tam);
in >> vet;

for (int i = 0; i < 50; i++)
cout << vet[i] << " " << i << endl;
cout << ns << endl;

return 0;
}

But the values returned for vet[] are not equal to the values of binary file.
Somebody can help me, please?
Thank you.

wysota
11th January 2008, 00:36
Don't use QDataStream unless you are sure you know what you are doing. Use QFile's QIODevice API instead.

QDataStream is a serialization mechanism, not a general purpose binary stream. If you want one, use std::fstream.

jaca
11th January 2008, 00:49
The values inside of file are all float.
Does not exist a form in Qt to catch these values of file?

jaca
11th January 2008, 02:06
They see as I made. It gave certain, but it wanted to use Qt.

ifstream file("wavemin_501ns.ad", ios::in | ios::binary);
file.seekg (0, ios::end);
int tam = file.tellg();
file.seekg (0, ios::beg);
qint64 ns = tam/sizeof(float);
QVector<float> vet(tam);
for(int i = 0; i < tam; i++)
file.read(reinterpret_cast < char * > (&vet[i]), sizeof(float));
file.close();
for (int i = 0; i < ns; i++)
cout << vet[i] << " " << i << endl;
cout << tam << " " << ns << endl;

wysota
11th January 2008, 11:52
The values inside of file are all float.
Oh, very nice, but float in which endianness? Of what length? QDataStream needs to take that all into consideration thus it stores additional information in the stream and expects that information to be present when reading the stream.

Does not exist a form in Qt to catch these values of file?
What for if std::fstream already does that? If you keep an unportable data in a file, you need an unportable solution to it. QDataStream is not one. Use QIODevice::read() and cast or convert the output into the format you know is suitable.

They see as I made. It gave certain, but it wanted to use Qt.
Qt is not a panaceum. It is meant to provide portable solutions and yours is not portable thus it is not supported by Qt.