Qt4: write QByteArray to file with filename?
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!
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);
QDataStream & QDataStream::writeBytes ( const char * s, uint len )
int QDataStream::writeRawData ( const char * s, int len )