1. 程式人生 > >qt5.5 讀寫檔案的中文亂碼解決方案

qt5.5 讀寫檔案的中文亂碼解決方案

#include<QString>
#include<QSetting>

QString localToGBK(QString src)
{
	QString source = src;
	int len = source.length();
	if (len%2 == 1)
		source.append('a');
	QString qstr = QString::fromLocal8Bit(source.toStdString().c_str());
	QString retStr = QTextCodec::codecForName("gbk")->fromUnicode(qstr);
	if (len%2 == 1)
		retStr = retStr.left(retStr.length() -1);
	return retStr;
}

void testIni()
{
	Qstring file = ".\\test.ini";
	Qstring section = "section1";
	{
		QSetting setting(file, QSetting::IniFormat);
		setting.setIniCodec(QTextCodec::codecForName("UTF-8"));
		
		QString s = "中文字元";
		setting.setValue(section1 + "/key", s);
	}
	{
		QSetting setting(file, QSetting::IniFormat);
		setting.setIniCodec(QTextCodec::codecForName("UTF-8"));
		
		QString sKey = setting.value(section + "/key").toString();
		
		QTextStream(stdout << localToGBK(sKey);
	}
}

// 專案配置預設編碼UTF-8, 如果編碼是UTF-8則新增