在項目開發過程中,有一個需求,程序啓動時會定義一組全局變量,當用戶操作這些變量,做一些修改,需要記住用戶的操作,下次打開軟件,按照用戶上次設置的值進行計算顯示。
配置文件格式如下,非常簡單
在此解決思路是,先讀取配置文件,循環每讀一行,解析變量和它對應的值,全部存起來,然後用當前需要記錄的值,去集合中找,如果找到了,就更新值,如果沒找到就增加到集合中,最後全部再寫入文件。
#include <QtCore/QCoreApplication> #include <QFile> #include <QTextStream> #include <QDebug> void DumpCfg(const std::string& strName,const std::string& strValue) { QFile rfile("C:\\Users\\Administrator\\Desktop\\123.cfg"); if (!rfile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "Can't open the file!" << endl; } std::map<std::string, std::string> mvars; while (!rfile.atEnd()) { QByteArray line = rfile.readLine();//讀一行 QString strLine(line); if (strLine[0] == ';' || strLine.indexOf("--") !=-1) { continue; } int pos = strLine.indexOf("="); QString strVar = strLine.left(pos); QString strValue = strLine.right(strLine.length() - pos - 1); strValue = strValue.simplified();//返回一個字符串,該字符串已從開始和結束處刪除空白,並將內部包括ASCII字符’\t’,’\n’,’\v’,’\f’,’\r’和’ '.替換爲‘ ’,如果替換後有兩個空格的話,只保留一個空格。 std::string sVar = strVar.toLocal8Bit(); std::string sValue = strValue.toLocal8Bit(); mvars[sVar] = sValue; } rfile.close(); std::map<std::string, std::string>::iterator iter = mvars.find(strName); if (iter != mvars.end()) { iter->second = strValue; } else { mvars[strName] = strValue; } //寫文件 QFile wfile("C:\\Users\\Administrator\\Desktop\\123.cfg"); if (!wfile.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug() << "Can't open the file!" << endl; } QTextStream out(&wfile); for (std::map<std::string, std::string>::iterator iter = mvars.begin(); iter != mvars.end();++iter) { out << QString("%1=%2").arg(iter->first.c_str()).arg(iter->second.c_str()) << "\n"; } wfile.close(); } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); DumpCfg("abc", "10");//記錄修改過得變量 return a.exec(); }