[英]Qt4: write QByteArray to file with filename?
我在Qt 4中遇到了写入非文本文件的问题。 我有一个QByteArray数据,我想将它保存到特定目录中名为“some_name.ext”的文件:“C:// MyDir”。 我怎样才能做到这一点? 请注意,内容不是文本。
格式为“GIF”,Qt不支持。
QImage mainImage;
if (!mainImage.loadFromData(aPhoto.data))
return false;
if (!mainImage.save(imageName, imageFormat.toUtf8().constData()))
return false;
我想以某种方式绕过那个限制!
要将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();
在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();
当然,请记得检查错误。
另请注意,即使这回答了您的问题,但它可能无法解决您的问题。
您可以使用QDataStream来写入二进制数据。
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 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.