用BOOST读配置文件

来源:互联网 发布:球状闪电刘慈欣 知乎 编辑:程序博客网 时间:2024/05/20 11:20

#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());
}