C / C ++ Unix配置文件库

时间:2011-04-18 08:45:27

标签: c++ c unix configuration-files

在哪里可以找到用于读取和操作Unix配置文件的C或C ++库(format: name=value\n)?

4 个答案:

答案 0 :(得分:6)

我建议你使用boost :: property_tree库来实现C ++。它有安静的详细手册。此外,我建议您使用“info”配置文件。

配置文件示例:

; this is just comment line

firstParamSection 
{
   stringParam "string"
   intParam 10
}

从配置文件中检索此参数的代码示例:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <string>

int main (int argc, char *argv[]) {
  std::string testString;
  int testInt;

  boost::property_tree::ptree pTree;
  try {
    read_info("test/config/file/name", pTree);
  }
  catch (boost::property_tree::info_parser_error e) {
    std::cout << "error" << std::endl;
  }

  try {
    testString = pTree.get<std::string>("firstParamSection.stringParam");
    testInt = pTree.get<int>("firstParamSection.intParam");
  }

  catch(boost::property_tree::ptree_bad_path e) {
    std::cout << "error" << std::endl;
  }

答案 1 :(得分:2)

对于普通C,libconfuse非常好

答案 2 :(得分:1)

几个星期前,我自己为“info”样式配置文件编写了一个配置解析器。它完全符合XDG标准,部分可以嵌套,而且非常易于使用:

// read config file "barc" in directory $XDG_CONFIG_HOME/foo, e.g. /home/bwk/.config/foo/barc
config_read("foo", "barc");

// can read a specific file as well:
config_read_file("/etc/tralalarc");

// or from an open FILE *fp
config_read_fp(fp);

// or n characters directly from memory
config_read_mem(0xDEADBEEF, n);


// retrieve value associated with "key" in section "here", sub-section "my"
char *val = config_get("here.my.key");

您还可以设置/锁定包含注释的配置变量,并将配置写回磁盘。它非常自我解释,但缺乏文档。请参阅config.* here

我很乐意根据需要添加文档和/或界面。

答案 3 :(得分:1)

看看Augeas,这是非常普遍的。