1
2
3
4
5
6
7
8
9
10
11
bool writeTextFile(QString path, const QString& text, QTextCodec *codec)
{
QFile file(path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { }
QTextStream text_stream(&file);
text_stream.setGenerateByteOrderMark(true); // 调用这一句
text_stream.setCodec(codec);
text_stream << text;
file.close();
return true;
}

API说明:

void QTextStream::setGenerateByteOrderMark(bool generate)

If generate is true and a UTF codec is used, QTextStream will insert the BOM (Byte Order Mark) before any data has been written to the device. If generate is false, no BOM will be inserted. This function must be called before any data is written. Otherwise, it does nothing.