window下文件一般为GBK格式文件,而Linux系统下文件一般为UTF8文件,当文件读取格式不匹配时,读取到的数据显示为乱码,所以需要转码.
GBK格式文件读取
代码语言:javascript复制QFile file("GBK.txt");
file.open(QFile::ReadOnly | QFile::Text);
QTextCodec *codec = QTextCodec::codecForName("GBK");
QString content = codec->toUnicode(file.readAll());
qDebug()<<"Display GBK.txt file"<<content;
UTF8格式文件读取
代码语言:javascript复制QFile file("UTF8.txt");
file.open(QFile::ReadOnly | QFile::Text);
QTextCodec *codec = QTextCodec::codecForName("UTF8");
QString content = codec->toUnicode(file.readAll());
qDebug()<<"Display UTF8.txt File: "<<content;
输出
代码语言:javascript复制Display GBK.txt file "Hello world
中文
"
Display UTF8.txt File: "Hello world
你好
"
注意
- 使用QTextCodec前需要先构造QCoreApplication类或其派生类否则转码不成功.
源文件
代码语言:javascript复制#include <QCoreApplication>
#include <QFile>
#include <QTextCodec>
#include <QDebug>
static void displayGBKFile()
{
QFile file("GBK.txt");
file.open(QFile::ReadOnly | QFile::Text);
QTextCodec *codec = QTextCodec::codecForName("GBK");
QString content = codec->toUnicode(file.readAll());
qDebug()<<"Display GBK.txt file"<<content;
}
static void displayUTF8File()
{
QFile file("UTF8.txt");
file.open(QFile::ReadOnly | QFile::Text);
QTextCodec *codec = QTextCodec::codecForName("UTF8");
QString content = codec->toUnicode(file.readAll());
qDebug()<<"Display UTF8.txt File: "<<content;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
displayGBKFile();
displayUTF8File();
return a.exec();
}
源码地址
代码语言:javascript复制https://github.com/myqtdemo/QtUTF8AndGBKCoding.git