概述
在日常文件读取中,读取中文文件很可能出现乱码。
那么对于中文编码的文件编码识别则至关重要,这个问题在 Qt 中可以很好的解决。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| int DataCsv::findCode(const QString &fileName) { int code = 3; QFile file(fileName); if (file.open(QIODevice::ReadOnly)) { QByteArray buffer = file.read(3); quint8 b1 = buffer.at(0); quint8 b2 = buffer.at(1); quint8 b3 = buffer.at(2); if (b1 == 0xFF && b2 == 0xFE) { code = 1; } else if (b1 == 0xFE && b2 == 0xFF) { code = 2; } else if (b1 == 0xEF && b2 == 0xBB && b3 == 0xBF) { code = 4; } else { QTextCodec::ConverterState state; QTextCodec *codec = QTextCodec::codecForName("utf-8"); codec->toUnicode(buffer.constData(), buffer.size(), &state); if (state.invalidChars > 0) { code = 0; } }
file.close(); }
return code; }
|