PDA

View Full Version : Reading a binary file with QT



YuriyRusinov
19th December 2012, 13:24
I have to read binary file via Qt. In console application I make



FILE * fid5 = fopen ("./test_data/source.rgg", "rb");

...
for (int i=1; i<=na; i++)
{
fread (st+i-1, sizeof (unsigned long), nd2, fid5);
...
}


and all work fine. In Qt application I try


QString fileName = QFileDialog::getOpenFileName (this, tr("Select
source file"), QDir::currentPath(), tr("All files (*)"));
if (fileName.isEmpty())
return;
...

QFile * fData = new QFile (fileName);

for (int i=1; i<=na; i++)
{
char * colData = new char [nd2*sizeof (unsigned long)];
qint64 colLength = fData->readLine (colData, nd2*sizeof
(unsigned long));
if (colLength < 0)
{
qDebug () << __PRETTY_FUNCTION__ << QString ("Read error");
continue;
}
QByteArray buff (colData);
delete [] colData;
//qDebug () << __PRETTY_FUNCTION__ << i << buff;

QBuffer lBuf (&buff);
lBuf.open (QIODevice::ReadOnly);
QDataStream numStr (&lBuf);
quint64 num;
for (int ii=0; ii<nd2; ii++)
{
numStr >> num;
qDebug () << __PRETTY_FUNCTION__ << num;
st[ii] = num;
}
...
}


And for the same file in debug numbers do not read properly.
Thanks a lot.

Lesiok
19th December 2012, 15:38
First of all why in Qt code You are using readLine ? This method is for reading character data not binary.

YuriyRusinov
19th December 2012, 19:44
First of all why in Qt code You are using readLine ? This method is for reading character data not binary.

I try using method read, such this


char * colData = new char [nd2*sizeof (unsigned long)];
qint64 colLength;// = nd2*sizeof (unsigned long);
//stStream.readBytes (colData, colLength);
colLength = fData.read (colData, nd2*sizeof (unsigned long));
if (colLength <= 0)
{
qDebug () << __PRETTY_FUNCTION__ << i << QString ("Read error");
return;
}
QByteArray buff (colData);
delete [] colData;


but error was arises. Which way I have to trace this error ?

wysota
19th December 2012, 19:55
You forgot to open the file.

ChrisW67
20th December 2012, 03:43
Once you have the file open...

You are reading nd2 unsigned longs (probably 4 bytes each) from the file and then trying to extract nd2 unsigned 64-bit integers from that data (lines 26 and 29).

YuriyRusinov
20th December 2012, 06:39
Sorry, I skip this


if (!fData.open (QIODevice::ReadOnly | QIODevice::Unbuffered))
return;

But nothing changes.

wysota
20th December 2012, 08:58
What else did you skip? :)

BTW. You are reading data using QDataStream. Was it written using QDataStream?

YuriyRusinov
21st December 2012, 07:14
Problem was in environment. I forgot define macro _FILE_OFFSET_BITS=64 in 32 bit environment. Thanks a lot.