利用Qsettings包一个类 RWIniFile, writeIni方法写文件, readIni方法读文件
rwinifile.h
#ifndef RWINIFILE_H #define RWINIFILE_H #include <QtGui> class RWIniFile { public: RWIniFile(); bool static writeIni(QString path, QString section,QString keyword, QString keyvalue,bool clear_flag); bool static writeIni(QString path, QString section,QString keyword, QString keyvalue); QString static readIni(QString path, QString section,QString keyword, QString &keyvalue); }; #endif // RWINIFILE_H
rwinifile.cpp
#include "rwinifile.h" RWIniFile::RWIniFile() { } bool RWIniFile::writeIni(QString path, QString section,QString keyword, QString keyvalue) { if(path == QString("")) { return false; } else { //创建配置文件操作对象 QSettings *config = new QSettings(path, QSettings::IniFormat); //将信息写入配置文件 config->beginGroup(section); config->setValue(keyword, keyvalue); config->endGroup(); if(config) { delete config; } return true; } } bool RWIniFile::writeIni(QString path, QString section,QString keyword, QString keyvalue, bool clear_flag) { if(path == QString("")) { return false; } else { //创建配置文件操作对象 QSettings *config = new QSettings(path, QSettings::IniFormat); if( clear_flag == true ) config->clear(); //将信息写入配置文件 config->beginGroup(section); config->setValue(keyword, keyvalue); config->endGroup(); if(config) { delete config; } return true; } } QString RWIniFile::readIni(QString path, QString section,QString keyword, QString &keyvalue) { if(path == QString("")) { return false; } else { //创建配置文件操作对象 QSettings *config = new QSettings(path, QSettings::IniFormat); keyvalue = config->value(section + "/" + keyword).toString(); if(config) { delete config; } return keyvalue; } }
main函数里的使用方法
RWIniFile::writeIni("log.txt", "config1", "key1", "test"); RWIniFile::writeIni("log.txt", "config1", "key2", "test2"); RWIniFile::writeIni("log.txt", "config2", "key1", "test"); RWIniFile::writeIni("log.txt", "config2", "key2", "test2"); RWIniFile::writeIni("log.txt", "config2", "key2", "test2"); //写入不清除原配置 RWIniFile::writeIni("log.txt", "config3", "key", "hello world", false); //如果clear_flag=true,清除原配置 QString keyword; keyword = RWIniFile::readIni(QString("log.txt"), QString("config3"), QString("key"), keyword); //读配置文档 qDebug() << keyword ;