Qt读取保存不同编码的记事本,解决乱码问题

对于配置文件,不同客户保存的编码也不一致,直接使用QFile 读取,很可能会出现乱码情况,解决方法就是使用类QTextStream 来读取每行数据,先看下QTextStream 帮助文档上的解释:

Internally, QTextStream uses a Unicode based buffer, and QTextCodec is
used by QTextStream to automatically support different character sets.
By default, QTextCodec::codecForLocale() is used for reading and
writing, but you can also set the codec by calling setCodec().

大概意思就是QTextStream 会自动支持不同的字符集,所以直接用这个类,还不用自己每个编码去转化,简单方便。

    QString filePath = "../config.txt";
    
    QFile file(filePath);
  
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream textStream(&file);
        while(!textStream.atEnd())
        {
            QString line = textStream.readLine();
            qDebug()<< line;
        }
        file.close();
    }

可是问题又来,如果配置文件中带中文字符,读取就会乱码,QTextStream 还可以设置编码,解决思路就是,先判断这个文件是什么编码,再设置QTextStream 编码。

//判断文件编码

    QFile file(filePath);
    QString codeType = "UTF-8";
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QByteArray text = file.readAll();
        QTextCodec::ConverterState state;
        QTextCodec *codec = QTextCodec::codecForName("UTF-8");
        codec->toUnicode(text.constData(), text.size(), &state);

        if (state.invalidChars > 0){
            codeType = "GBK";
        }
        file.close();
    }
    
 //读取文件
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream textStream(&file);
        textStream.setCodec(codeType.toLatin1());
        while(!textStream.atEnd())
        {
            QString line = textStream.readLine();
            qDebug()<< line;
        }
        file.close();
    }

你可能感兴趣的:(QT,C++,unicode,utf,qt,codec,c++)