Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 840
Don Angelo Annoni Avatar asked Oct 20 '12 11:10

Don Angelo Annoni


2 Answers

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.

like image 108
Nikos C. Avatar answered Oct 21 '22 23:10

Nikos C.


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 )
like image 22
Yuan Avatar answered Oct 21 '22 21:10

Yuan