栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++读取配置文件的示例代码

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++读取配置文件的示例代码

代码地址

https://github.com/gongluck/Code-snippet/tree/master/cpp/config

需求

开发中,读取配置文件信息必不可少。Windows平台有现成的API可用,也很方便。但是一旦项目迁移到Linux平台下,原先在Windows平台下的代码就全部作废。所以,实现一套跨平台的配置文件读取功能代码可以节省不少的劳动力。

实现

依赖于boost的ini_parser,可以实现跨平台读取ini格式的配置文件。

// config.h


// Profile read, dependent on boost

#pragma once

#include 
#include 
#include 

namespace gconf
{
class config
{
public:
  int open(const char *configfile);
  template 
  int read(const char *session, const char *key, T &value, const char *configfile = nullptr)
  {
    if (configfile != nullptr && open(configfile) != 0)
    {
      return -1;
    }

    try
    {
      auto lvbtItems = lvptProperties_.get_child(session);
      value = lvbtItems.get(key);
    }
    catch (std::exception &e)
    {
      std::cerr << __FILE__ << " : " << __LINE__ << " : " << e.what() << std::endl;
      return -1;
    }

    return 0;
  }
  int readall(const char *session,
 std::vector> &results,
 const char *configfile = nullptr);

private:
  boost::property_tree::ptree lvptProperties_;
};
} // namespace gconf
// config.cpp


#include "config.h"
#include 

namespace gconf
{
int config::open(const char *configfile)
{
  if (configfile == nullptr)
  {
    return -1;
  }

  try
  {
    boost::property_tree::ini_parser::read_ini(configfile, lvptProperties_);
  }
  catch (std::exception &e)
  {
    std::cerr << __FILE__ << " : " << __LINE__ << " : " << e.what() << std::endl;
    return -1;
  }

  return 0;
}

int config::readall(const char *session,
   std::vector> &results,
   const char *configfile )
{
  if (configfile != nullptr && open(configfile) != 0)
  {
    std::cerr << __FILE__ << " : " << __LINE__ << " : "
  << " can not open " << configfile << std::endl;
    return -1;
  }

  try
  {
    auto lvbtItems = lvptProperties_.get_child(session);
    for (const auto &i : lvbtItems)
    {
      results.push_back(std::make_pair(i.first.data(), i.second.data()));
    }
  }
  catch (std::exception &e)
  {
    std::cerr << __FILE__ << " : " << __LINE__ << " : " << e.what() << std::endl;
    return -1;
  }

  return 0;
}
} // namespace gconf
// testcode
#include 

#include "../config/config.h"

#define CHECKRET(ret)
if(ret != 0)
{
  std::cin.get();
  return ret;
}

int main()
{
  gconf::config conf;
  auto ret = conf.open("./config.ini");
  CHECKRET(ret);
  int file = 0;
  ret = conf.read("log", "file", file);
  CHECKRET(ret);
  std::vector>kvs;
  ret = conf.readall("log", kvs);
  CHECKRET(ret);
  return 0;
}

以上就是C++读取配置文件的示例代码的详细内容,更多关于C++读取配置文件的资料请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/61393.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号