ini读写会遇到一个很难逃过的一个问题,读写中文,而Qt的ini操作类QSetting对其支持不是很友好,于是就有了自己重写这两个读写接口的想法,实现如下:
解决问题:读写含有group,key,value为中文的ini文件;
解决办法:用QFile读写ini文件,根据[],和“=”等特殊字符进行判断,做点简单的逻辑处理;
适用于:读写编码为GB2312的ini文件;
读Ini文件:
QVariant ReadIni(QString filePath, QString group, QString key, QString deaultValue)
{
//1.读文件
QString szIniPath = filePath;
bool bExistFile = false;
szIniPath = szIniPath.replace('\\', '/');
bExistFile = QFile::exists(szIniPath);
if (!bExistFile){
qDebug()<<QString("ReadIni: File[%1] is not exist!").arg(filePath);
return QVariant(deaultValue);
}
QFile file(szIniPath);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug()<<QString("ReadIni: Can't open the file[%1]!").arg(filePath);
return QVariant(deaultValue);
}
bool containGroupFlg=false;
QString returnStr = "";
while(!file.atEnd())
{
QByteArray baLine = file.readLine();//读取一行的信息
QString szLine = QString::fromLocal8Bit(baLine, baLine.length());
if(szLine.contains(group)){
containGroupFlg=true;//当前listIndex为group匹配index
continue;
}
if(containGroupFlg){
if(szLine.contains("[")){
qDebug() << QString("ReadIni: %1/%2 not find in file[%3]").arg(group).arg(key).arg(filePath);
return QVariant(deaultValue);
}else{
if(szLine.contains("=")){
QString groupValue = szLine.section("=",0,0);
if(groupValue.contains(key)){
returnStr = szLine.section("=",1,1);
if(returnStr.endsWith('\n')){
returnStr.remove('\n');
}
file.close();
return QVariant(returnStr);
}
}
}
}
}
file.close();
return QVariant(deaultValue);
}
写Ini文件:
void WriteIni(QString inifilePath, QString group, QString key, QString strValue)
{
//QWriteLocker locker(&lock);
QStringList stOpertorRecordList;
stOpertorRecordList.clear();
//1.读文件
QString szIniPath = inifilePath;
bool bExistFile = false;
szIniPath = szIniPath.replace('\\', '/');
bExistFile = QFile::exists(szIniPath);
if (!bExistFile){
qDebug()<<"File is not exist!"<<endl;
return;
}
QFile file(szIniPath);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug()<<"Can't open the file!"<<endl;
return;
}
while(!file.atEnd())
{
QByteArray baLine = file.readLine();
QString szLine = QString::fromLocal8Bit(baLine, baLine.length());
stOpertorRecordList.append(szLine);
}
file.close();
//2.修改value
bool containGroupFlg=false;
for(int listIndex=0; listIndex<stOpertorRecordList.count(); listIndex++)
{
QString str = stOpertorRecordList.at(listIndex);
if(str.contains(group)){
containGroupFlg=true;//当前listIndex为group匹配index
continue;
}
if(containGroupFlg){
if(str.contains("[")){
qDebug() << "no match group/key.";
return;
}else{
if(str.contains(key)){
QString finalStr = QString("%1=%2\n").arg(key).arg(strValue);
stOpertorRecordList[listIndex] = finalStr;
break;
}
}
}
}
//3.写
if(file.open(QIODevice::ReadWrite | QIODevice::Text))
{
file.resize(0); //清空文件
QTextStream stream(&file);
stream.setCodec(QTextCodec::codecForName("GB18030"));
stream.seek(file.size());
for(int n=0; n<stOpertorRecordList.size(); n++)
{
QString szStr = stOpertorRecordList.at(n);
stream<<szStr;
}
}
file.close();
}
|