用BOOST读配置文件

#include <string>
#include <iostream>
using namespace std;
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>

class CBoostConfigFile
{
public:
 typedef boost::property_tree::ptree str_ptree;
private:
 string m_filename;
 boost::property_tree::ptree m_protree;
 
public:
 CBoostConfigFile(string filename){
  m_filename=filename;
  try{
   boost::property_tree::ini_parser::read_ini(m_filename, m_protree);
  }catch(std::exception &e)
  {
   std::cout<<e.what()<<std::endl;
  }
 };
 virtual ~CBoostConfigFile(){};

 bool GetParam(const char *name,string &param)
 {
  if(m_filename.length()==0)
   return false;
  try{
   param = m_protree.get<string>(name);
  }catch(std::exception &e)
  {
   std::cout<<e.what()<<std::endl;
   return false;
  }
  return true;
 }

 bool GetParam(const char *name,long &param)
 {
  if(m_filename.length()==0)
   return false;
  try{
   param = m_protree.get<long>(name);
  }catch(std::exception &e)
  {
   std::cout<<e.what()<<std::endl;
   param=0;
   return false;
  }
  return true;
 }

 bool GetParam(const char *name,int &param)
 {
  if(m_filename.length()==0)
   return false;
  try{
   param = m_protree.get<int>(name);
  }catch(std::exception &e)
  {
   std::cout<<e.what()<<std::endl;
   param=0;
   return false;
  }
  return true;
 }

 bool GetChile(const char *name,str_ptree&chiletree)
 {
  try{
  chiletree= m_protree.get_child(name);
  }catch(std::exception &e)
  {
   std::cout<<e.what()<<std::endl;
   return false;
  }
  return true;
 }
};

 

test:

string str;
config.GetParam("aa.1",str);
printf("getstr:%s\r\n",str.c_str());
config.GetParam("bb",str);
printf("cqnum:%s\r\n",str.c_str());

boost::property_tree::ptree child1;
config.GetChile("config1",child1);
for(boost::property_tree::ptree::iterator pos=child1.begin(); pos != child1.end(); ++pos)
{
 string name=pos->second.data();
 string value=pos->first.data();
 printf("%s\t%s\r\n",name.c_str(),value.c_str());
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值