Qt4: write QByteArray to file with filename?
Solution 1
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.
Solution 2
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 )
Don Angelo Annoni
Updated on August 03, 2020Comments
-
Don Angelo Annoni over 3 years
I'm having trouble in Qt 4 with writing to non-text files. I have a QByteArray data and I want to save it to a file with name "some_name.ext" in specific directory: "C://MyDir". How can I do this? Note that the content is not textual.
The format is "GIF" and it is not supported by Qt.
QImage mainImage; if (!mainImage.loadFromData(aPhoto.data)) return false; if (!mainImage.save(imageName, imageFormat.toUtf8().constData())) return false;
I want to bypass somehow that restriction!