C++ Qt4:用文件名将 QByteArray 写入文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12988131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Qt4: write QByteArray to file with filename?
提问by Don Angelo Annoni
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.
我在 Qt 4 中写入非文本文件时遇到问题。我有一个 QByteArray 数据,我想将它保存到特定目录中名为“some_name.ext”的文件中:“C://MyDir”。我怎样才能做到这一点?请注意,内容不是文本。
The format is "GIF" and it is not supported by Qt.
格式为“GIF”,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!
我想以某种方式绕过那个限制!
回答by Nikos C.
To write a QByteArray to a file:
将 QByteArray 写入文件:
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 QSaveFileinstead 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:
在 Qt 5(5.1 及更高版本)中,您应该在保存新的完整文件时使用QSaveFile(而不是修改现有文件中的数据)。这样就避免了写操作失败时丢失旧文件的情况:
// 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.
另请注意,即使这回答了您的问题,它也可能无法解决您的问题。
回答by Yuan
You can use QDataStream to write binary data.
您可以使用 QDataStream 写入二进制数据。
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 )