处理INI文件

简单的在开源中国上搜索了一下INI相关的项目,找到两个:MiniINI和SimpleINI。

 

MiniINI是一个开源的,非常高效的,并且非常容易上手的INI库。使用C++实现的,同时也可以操作CFG文件。它本身不依赖除标准库以外的任何库文件,能够在支持C99的各种编译器上编译。采用MIT/X许可证,有兴趣的可以参考:https://code.launchpad.net/miniini。到现在为止,项目本身并不支持对INI文件的写操作,因此只有忍痛割爱了。它的接口非常简洁。可以看看示例代码(本身包含STL版本和非STL版本,示例是一个STL的版本示例)。可以看出函数的命名非常易懂,也很容易使用。

 

#include<miniini.h> #include<iostream> int main() { INIFile ini; std::string fname = "example.ini"; if(!ini.OpenFile(fname)) std::cout << "ERROR: Could not open example.ini" << std::endl; std::string sname = "general"; INISection * general = ini.GetSection(sname); if(!general) std::cout << "ERROR: Missing section [general] in example.ini" << std::endl; std::string appname; int appbuild; float brightness; bool fullscreen; std::string appname_tag = "AppName"; std::string appbuild_tag = "AppBuild"; std::string brightness_tag = "Brightness"; std::string fullscreen_tag = "FullScreen"; if(!general->ReadString(appname_tag, appname)) std::cout << "ERROR: Missing tag AppName= in section [" << sname << "] in example.ini" << std::endl; if(!general->ReadInt(appbuild_tag, appbuild)) std::cout << "ERROR: Missing or invalid tag AppBuild= in section [" << sname << "] in example.ini" << std::endl; if(!general->ReadFloat(brightness_tag, brightness)) std::cout << "ERROR: Missing or invalid tag Brightness= in section [" << sname << "] in example.ini" << std::endl; if(!general->ReadBool(fullscreen_tag, fullscreen)) std::cout << "ERROR: Missing or invalid tag FullScreen= in section [" << sname << "] in example.ini" << std::endl; std::cout << appname << " build " << appbuild << " fullscreen is " << fullscreen << " brightness is " << brightness << std::endl; return 0; }

 

SimpleINI也是一个跨平台的操作INI文件的开源库。支持ASCII,MBCS和Unicode。使用的同样是MIT的许可。有兴趣的可以参考http://code.jellycan.com/simpleini/。由于它支持读写INI文件,详细看看怎么使用它。

 

简单的查询和更改操作。首先创建一个INI对象,设置字符编码,从文件中加载INI内容(也支持内存加载),然后查询一个Section中的Key值,最后赋其一个新值。

CSimpleIniA ini; ini.SetUnicode(); ini.LoadFile("myfile.ini"); const char * pVal = ini.GetValue("section", "key", "default"); ini.SetValue("section", "key", "newvalue");

 

从文件和字符串中加载数据:

CSimpleIniA ini(a_bIsUtf8, a_bUseMultiKey, a_bUseMultiLine); SI_Error rc = ini.LoadFile(a_pszFile); if (rc < 0) return false;

td::string strData; rc = ini.LoadData(strData.c_str(), strData.size()); if (rc < 0) return false;

 

获取所有的Section:

 

CSimpleIniA::TNamesDepend sections; ini.GetAllSections(sections);

 

获取Section下面的所有Keys:

 

CSimpleIniA::TNamesDepend keys; ini.GetAllKeys("section-name", keys);

 

获取Key所对应的值:

 

const char * pszValue = ini.GetValue("section-name", "key-name", NULL /*default*/);

 

 

 

 

 

你可能感兴趣的:(String,ini,Build,float,编译器,跨平台)