博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用boost中的property_tree实现配置文件
阅读量:7238 次
发布时间:2019-06-29

本文共 2488 字,大约阅读时间需要 8 分钟。

property_tree是专为配置文件而写,支持xml,ini和json格式文件
 
ini比较简单,适合简单的配置,通常可能需要保存数组,这时xml是个不错的选择。
 
使用property_tree也很简单,boost自带的帮助中有个5分钟指南
 
这里写一下使用xml来保存多维数组,在有些情况下一维数组并不能满足要求。
举个简单的例子吧:
xml格式如下:
  
3
  
    
    
23
    
hugo
  
  
    
23
     
mayer
  
  
    
30
    
boy
  
  
定义结构体如下:
1 struct person  2 {
3 int age; 4 std::string name; 5 }; 6 7 struct debug_persons 8 {
9 int itsTotalNumber; 10 std::vector
itsPersons; 11 void load(const std::string& filename); 12 void save(const std::string& filename); 13 };
2个载入和保存的函数:
1 void debug_persons::save( const std::string& filename )  2 {
3 using boost::property_tree::ptree; 4 ptree pt; 5 6 pt.put("debug.total", itsTotalNumber); 7 8 BOOST_FOREACH(const person& p,itsPersons) 9 {
10 ptree child; 11 child.put("age",p.age); 12 child.put("name",p.name); 13 pt.add_child("debug.persons.person",child); 14 } 15 // Write property tree to XML file 16 write_xml(filename, pt); 17 18 } 19 20 void debug_persons::load( const std::string& filename ) 21 {
22 using boost::property_tree::ptree; 23 ptree pt; 24 25 read_xml(filename, pt); 26 itsTotalNumber = pt.get
("debug.total"); 27 28 BOOST_FOREACH(ptree::value_type &v, pt.get_child("debug.persons")) 29 { 30 //m_modules.insert(v.second.data()); 31 person p; 32 p.age = v.second.get
("age"); 33 p.name = v.second.get
("name"); 34 itsPersons.push_back(p); 35 } 36 }
main中的代码
1 int _tmain(int argc, _TCHAR* argv[])  2 {
3 4 try 5 {
6   debug_persons dp; 7   dp.load("debug_persons.xml"); 8   std::cout<
<
这里为了调试输出增加了以下代码:
1 std::ostream& operator<<(std::ostream& o,const debug_persons& dp)  2 {
3   o << "totoal:" << dp.itsTotalNumber << "\n"; 4   o << "persons\n"; 5   BOOST_FOREACH(const person& p,dp.itsPersons) 6   {
7     o << "\tperson: Age:" << p.age << " Nmae:" << p.name << "\n"; 8   } 9 return o; 10 }
ps:需要包含以下文件
1 #include 
2 #include
3 #include
4 #include
5 #include
6 #include
7 #include

转载地址:http://iprfm.baihongyu.com/

你可能感兴趣的文章
PostgreSQL的递归查询(with recursive)
查看>>
iOS 改变字体行间距与字间距
查看>>
美丽说2012校招笔试面试全过程
查看>>
图像处理基础(七)图像的PCA(主成分分析)降维
查看>>
Math-Model(三)高斯羽烟模型计算气体扩散浓度
查看>>
ActionContext和ServletActionContext小结
查看>>
expect脚本语言编写
查看>>
Apache优化:修改最大并发连接数
查看>>
求职充电 | 这些实战干货你get了吗?
查看>>
KeyMob移动聚合广告平台:APP开发者怎样将广告收益最大化
查看>>
redis-cluster研究和使用
查看>>
关于驰骋工作流引擎ccbpm 在工业自动化环境下的应用演示实例
查看>>
【序言】 高效高可靠消息服务器构建
查看>>
每天一个linux命令(6):rmdir 命令
查看>>
第六周作业
查看>>
浅谈Vim
查看>>
高端数据中心交换机散热系统大比拼
查看>>
Jira Epic在完成状态时,如何让Epic在Scrum面板待办事项中不显示?
查看>>
整理一下Entity Framework的查询
查看>>
添加引号的 java 正则表达式5
查看>>