通常,为了保存各种系统配置,我们可以通过写注册表或者写ini文件的方式来进行。这里,我就来举例说明如何用qt来实现ini文件的写入和读取。 假如,需要在C盘根目录下面建立一个名为config.ini的文件,里面有一个section叫做“path”,该section下面,有一个key叫做libpath,其值为“c://lib”,也就是下图所示的样子,
之后,我们还将其中的数值读取出来,那么,下面的代码可以作为参考: #include <QtGui/QApplication>
#include <QSettings>
#include <QStringList>
#include <QVariant>
#include <QDebug> int main(int argc, char *argv[])
{
QApplication a(argc, argv); QSettings *configIni = new QSettings("c://config.ini", QSettings::IniFormat, 0);
configIni->beginGroup("path");
configIni->setValue("libPath", "c://lib");
configIni->endGroup();
delete configIni; QSettings *readIni = new QSettings("c://config.ini", QSettings::IniFormat, 0);
readIni->beginGroup("path");
QStringList keys = readIni->allKeys();
QVariant *var = new QVariant;
for(int i=0; i<keys.size(); i++)
{
qDebug()<<keys<<endl;
QString str = readIni->value(keys).toString();
qDebug()<<"str = "<<str<<endl;
}
delete readIni;
delete var; return a.exec();
}
//================================================================ void WriteSettings() { //QSettings settings("Software Inc", "Spreadsheet"); // windows在注册表中建立建 Software Inc -> Spreadsheet QSettings settings("Option.ini", QSettings::IniFormat); // 当前目录的INI文件 settings.beginGroup("DevOption"); settings.setValue("mainFun", 25); settings.setValue("subFun", 40); settings.setValue("service", 1); settings.endGroup(); } void ReadSettings() { QSettings settings("Option.ini", QSettings::IniFormat); int mainFun = settings.value("DevOption/mainFun").toInt(); int subFun = settings.value("DevOption/subFun").toInt(); QString service = settings.value("DevOption/service").toString();
qDebug() << "service" << service; qDebug() << "mainFun" << mainFun; qDebug() << "subFun" << subFun; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); WriteSettings(); ReadSettings(); return a.exec(); }
|