PDA

View Full Version : Reading/writing data to binary file



DiamonDogX
23rd July 2009, 16:50
I am basically writing a bunch of qint32 values to a binary file and I want to be able to seek to an offset of the file and read a value back. So I am doing the following for writing and reading:


QFile file( "MyFile" );
if( file.open( QFile::WriteOnly | QFile::Truncate ) )
{
for( int i = 0; i < 10; i++ )
{
qint32 exampleNum = 42;
file.write( ( char * )( &exampleNum ), sizeof( exampleNum) );
}
file.close();
}



QFile file( "MyFile" );
if( file.open( QFile::ReadOnly ) )
{
if( file.seek( 4) )
{
char * dataRead = new char[ sizeof( qint32 ) ];
qint64 numBytesRead = file.read( dataRead, sizeof( qint32 ) );
if( numBytesRead == sizeof( qint32 ) )
{
QByteArray dataBytes( dataRead );
bool ok = false;
qint32 value = dataBytes.toInt( &ok ); // "value" ends up 0
if( ok )
{
cout << value; // never gets here
}
}
}
}

Seem to be having trouble reading a value back...

Lykurg
23rd July 2009, 16:58
Hey, just a quick suggestion: you might want have a look at QDataStream. Could make your live much more easier.

DiamonDogX
23rd July 2009, 19:02
Yeah I've used it before... doesn't seem to be helping me in this case...

DiamonDogX
23rd July 2009, 19:24
I take that back! I mixed it in with the code, changed some things, and I can read and write the integers now...