【问题标题】:C/C++ Unix configuration file library [closed]C/C++ Unix 配置文件库 [关闭]
【发布时间】:2011-04-18 08:45:27
【问题描述】:

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

【问题讨论】:

  • C(或 C++)标准库?
  • 我相信有人会提到 C++ 的 boost::program_options 和 C 的 getopt
  • 对不起,这听起来像是一个愚蠢的问题,我对 C/C++ 很陌生。
  • 我正在为 unix-ish 系统编写程序。我需要一个简单的配置文件,它的行为就像 *nix 管理员所期望的那样。

标签: c++ c unix configuration-files


【解决方案1】:

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

配置文件示例:

; 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;
  }

【讨论】:

  • 如果你想使用 strcitly (name = "value") 格式 boost 也支持它。只需使用 ini_parser 而不是 info_parser。
  • 这似乎是我正在寻找的解决方案。但是,我认为我将首先推出自己的解决方案(用于教育目的),然后在以后的项目中切换到 boost。谢谢!
【解决方案2】:

对于纯 C,libconfuse 相当不错

【讨论】:

  • 有趣,看起来类似于 puppetmaster 使用的格式。
【解决方案3】:

几周前,我自己为“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");

您还可以设置/锁定配置变量,包括 cmets 并将配置写回磁盘。这很不言自明,但缺少文档。见config.*here

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

【讨论】:

  • 感谢您的示例代码。因为我才刚接触 C 语言几天,这将帮助我理解文件和字符串处理。
【解决方案4】:

看看Augeas,它非常通用。

【讨论】:

    猜你喜欢
    • 2010-09-13
    • 1970-01-01
    • 2016-03-16
    • 2011-08-07
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多