Qt读取TXT文件时,GBK与UTF-8编码判断

读取txt文件时,很多时候无法获取文件的编码格式。如果直接进行使用,则有可能出现乱码。需要在使用前将其转为Unicode(Qt的默认编码格式)。

虽然实际的编码格式种类非常多,但平常主要使用的有GBK与UTF-8两种。可以依次尝试转换,如果转换出现无效字符则认为不是该种编码格式。

QString GetCorrectUnicode(const QByteArray &ba)
{
    QTextCodec::ConverterState state;
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QString text = codec->toUnicode( ba.constData(), ba.size(), &state);
    if (state.invalidChars > 0)
    {
        text = QTextCodec::codecForName( "GBK" )->toUnicode(ba);
    }
    else
    {
        text = ba;
    }

    return text;
}

  

qt-creator的编码格式,通过帮助文档查看:

大概有如下的编码格式:

Big5
Big5-HKSCS
CP949
EUC-JP
EUC-KR
GB18030
HP-ROMAN8
IBM 850
IBM 866
IBM 874
ISO 2022-JP
ISO 8859-1 to 10
ISO 8859-13 to 16
Iscii-Bng, Dev, Gjr, Knd, Mlm, Ori, Pnj, Tlg, and Tml
KOI8-R
KOI8-U
Macintosh
Shift-JIS
TIS-620
TSCII
UTF-8
UTF-16
UTF-16BE
UTF-16LE
UTF-32
UTF-32BE
UTF-32LE
Windows-1250 to 1258

原文地址:https://www.cnblogs.com/senior-engineer/p/9198729.html