如何确定文本文件是否具有 Unicode BOM?

How to determine if the text file has a Unicode BOM or not?

如何使用Qt检测BOM 类?我想做的是读取一个 UTF-8 文件,处理其内容并将其写回。我可以选择使用 QTextStream 设置或删除 BOM,但我看不到任何方法来保留其原始状态(存在或不存在),因为我无法查询它。

可以使用QTextCodec::codecForUtfText判断字节数组是否有BOM:

QFile *file = ...;
bool hasByteOrderMark = QTextCodec::codecForUtfText(file->peek(4), nullptr) != nullptr;
// QTextCodec is owned by Qt - don't free

作为一种捷径,您可以利用(未记录的)事实,即如果 QTextStream 未能从流中检测到编码,它将关闭 generateByteOrderMark

QTextStream stream(file);
stream.setAutoDetectUnicode(true);
stream.setCodec(QTextCodec::codecForMib(106));    // default to UTF-8
stream.setGenerateByteOrderMark(true);

stream.readLine();    // detect codec and possibly switch off generateByteOrderMark

int mib = stream.codec()->mibEnum();    // detected codec, or UTF-8 (default set above)
bool hasByteOrderMark = stream.generateByteOrderMark();

这是未记录的行为,因此如果您想依赖它,您可能需要进行测试。