将 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();
当然,记得检查错误。
另请注意,即使这回答了您的问题,也可能无法解决您的问题。