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.

// ... fill the array with data ...

// Save the data to a file.
QFile file("C:/MyDir/some_name.ext");

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");
// Calling commit() is mandatory, otherwise nothing will be written.

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");
QDataStream out(&file);

Then use

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


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

Need Your Help

How to bind an object list with thymeleaf?

java spring spring-mvc spring-boot thymeleaf

I am having a lot of difficulty with POSTing back a form to the controller, which should contain simply an arraylist of objects that the user may edit.

Stackoverflow due to long RDD Lineage

scala apache-spark rdd

I have thousands of small files in HDFS. Need to process a slightly smaller subset of files (which is again in thousands), fileList contains list of filepaths which need to be processed.