Qt4: write QByteArray to file with filename? Qt4: write QByteArray to file with filename? arrays arrays

Qt4: write QByteArray to file with filename?


To write a QByteArray to a file:

QByteArray data;// If you know the size of the data in advance, you can pre-allocate// the needed memory with reserve() in order to avoid re-allocations// and copying of the data as you fill it.data.reserve(data_size_in_bytes);// ... fill the array with data ...// Save the data to a file.QFile file("C:/MyDir/some_name.ext");file.open(QIODevice::WriteOnly);file.write(data);file.close();

In Qt 5 (5.1 and up), you should use QSaveFile instead when saving a new complete file (as opposed to modifying data in an existing file). This avoids the situation where you lose the old file if the write operation fails:

// Save the data to a file.QSaveFile file("C:/MyDir/some_name.ext");file.open(QIODevice::WriteOnly);file.write(data);// Calling commit() is mandatory, otherwise nothing will be written.file.commit();

Remember to check for errors, of course.

Also note that even though this answers your question, it probably doesn't solve your problem.


You can use QDataStream to write binary data.

QFile file("outfile.dat");file.open(QIODevice::WriteOnly);QDataStream out(&file);

Then use

QDataStream & QDataStream::writeBytes ( const char * s, uint len )

or

int QDataStream::writeRawData ( const char * s, int len )