boost 实现ini配置读写
1. Property Tree
Boost使用property_tree来实现ini的读写,同时也支持xml和json。
2. 示例
#include <stdio.h>
#include <string.h>
#include <boost/property_tree/ini_parser.hpp>
using namespace boost::property_tree;
int main()
{
//如果不想每次都带section可以先获取或设置child结点,
//如: pt_r.get_child("section");
// pt.put_child("section", pt_w);
std::string filename = "config.ini";
//write or update info to ini
ptree pt_w;
pt_w.put("section.key","value");
pt_w.put("section.key_num",8);
write_ini(filename, pt_w);
/*****************************
[section]
key=value
key_num=8
******************************/
//read info from ini
ptree pt_r;
read_ini(filename, pt_r);
std::string value = pt_r.get<std::string>("section.key", "");
int value_num = pt_r.get<int>("section.key_num", 0);
//update
pt_r.put<int>("section.key_num", 18);
write_ini(filename, pt_r);
/*****************************
[section]
key=value
key_num=18
******************************/
return 0;
}
3. 总结
从boost的官网介绍中,Property Tree库支持多种配置格式的读写,包括ini、xml和json,功能十分强大。
如果你的项目中技术栈已经引入了boost,那么不妨使用Property Tree替代其它第三方库。