首页 > 解决方案 > boost::program_options 配置文件格式

问题描述

我正在使用 boost::program_options 加载命令行参数。现在我想另外加载一个具有相同参数集的配置文件。我以非常标准的方式使用它:

ifstream ifs(filename.c_str());
if (ifs) {
    po::store(po::parse_config_file(ifs, optionsDescription), vm);
    po::notify(vm);
}

问题是 parse_config_file 接受以下标准格式的 ini 文件:

key1=value
key2 = value

但是我的文件不使用“等号”来分隔键和值,而只使用空格和/或制表符,如下所示:

key1 value
key2  value

出于兼容性原因,我需要保留这种格式。有没有办法通过 boost program_options 实现这一点?我找到了 command_line parses 的样式选项,但 parse_config_file 似乎没有这样的选项。

标签: c++boostdelimiterfile-formatboost-program-options

解决方案


根据source code, boost 似乎明确地寻找=符号。

所以没有直接的方法来处理你的文件格式。您可能必须更改 boost 源或将文件加载到内存并将值作为命令行输入处理。

else if ((n = s.find('=')) != string::npos) {
    string name = m_prefix + trim_ws(s.substr(0, n));
    string value = trim_ws(s.substr(n+1));

    bool registered = allowed_option(name);
    if (!registered && !m_allow_unregistered)
        boost::throw_exception(unknown_option(name));

    found = true;
    this->value().string_key = name;
    this->value().value.clear();
    this->value().value.push_back(value);
    this->value().unregistered = !registered;
    this->value().original_tokens.clear();
    this->value().original_tokens.push_back(name);
    this->value().original_tokens.push_back(value);
    break;

}

推荐阅读