Dar*_*ook 3 c++ boost boost-program-options
我有一个配置文件格式,我希望用Boost程序选项实现(因为我之前使用过该库),但我不得不实现这样的块:
label = whatever
depth = 3
start
source = /etc
dest = /tmp/etc/
end
start
source = /usr/local/include
dest = /tmp/include
depth = 1
end
Run Code Online (Sandbox Code Playgroud)
我在文档中读到了我可以拥有的内容[sections],所以我首先想知道这个:
label = whatever
depth = 3
[dir]
source = /etc
dest = /tmp/etc/
[dir]
source = /usr/local/include
dest = /tmp/include
depth = 1
Run Code Online (Sandbox Code Playgroud)
但是,如果我理解正确,dir它将成为变量名称的一部分,因此不可能重复,这是行不通的.那么我想知道要source转变为部分名称:
label = whatever
depth = 3
[/etc]
dest = /tmp/etc/
[/usr/local/include]
dest = /tmp/include
depth = 1
Run Code Online (Sandbox Code Playgroud)
这似乎是一种合理的方法吗?当我不提前知道部分名称时,我想知道如何迭代部分列表?
或者,有没有更好的方法来使用程序选项库来实现这一目标?
也许您应该使用Boostproperty_tree而不是program_options,因为您的文件格式似乎与Windows INI文件格式非常相似.Boost property_tree有一个INI文件的解析器(以及一个序列化器,以防你需要它).
然后,处理您的选项将通过遍历树来实现.不在节中的选项将位于树根下,节选项将位于该节的节点下.
你可以使用,program_options如果你真的想.关键是传递true最终参数parse_config_file,即allow_unregistered_options:
#include <iostream>
#include <sstream>
#include <boost/program_options.hpp>
static const std::string fileData = // sample input
"foo=1\n"
"[bar]\n"
"foo=a distinct foo\n"
"[/etc]\n"
"baz=all\n"
"baz=multiple\n"
"baz=values\n"
"a.baz=appear\n";
int main(int argc, char *argv[]) {
namespace po = boost::program_options;
std::istringstream is(fileData);
po::parsed_options parsedOptions = po::parse_config_file(
is,
po::options_description(),
true); // <== allow unregistered options
// Print out results.
for (const auto& option : parsedOptions.options) {
std::cout << option.string_key << ':';
// Option value is a vector of strings.
for (const auto& value : option.value)
std::cout << ' ' << value;
std::cout << '\n';
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这输出:
$ ./po
foo: 1
bar.foo: a distinct foo
/etc.baz: all
/etc.baz: multiple
/etc.baz: values
/etc.baz: appear
Run Code Online (Sandbox Code Playgroud)
但是,请注意,您使用此方法获得的是选项向量,而不是典型用法program_options生成的映射.因此,您最终可能会将parsed_options容器处理为可以更轻松地查询的内容,并且某些内容可能看起来像property_tree.
这是一个使用的类似程序property_tree.输入略有不同,因为property_tree不允许重复键.
#include <iostream>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
static const std::string fileData = // sample input
"foo=1\n"
"[bar]\n"
"foo=a distinct foo\n"
"[/etc]\n"
"foo=and another\n"
"baz=all\n";
static void print_recursive(
const std::string& prefix,
const boost::property_tree::ptree& ptree) {
for (const auto& entry : ptree) {
const std::string& key = entry.first;
const boost::property_tree::ptree& value = entry.second;
if (!value.data().empty())
std::cout << prefix + key << ": " << value.data() << '\n';
else
print_recursive(prefix + key + '.', value);
}
}
int main() {
namespace pt = boost::property_tree;
std::istringstream is(fileData);
pt::ptree root;
pt::read_ini(is, root);
print_recursive("", root);
return 0;
}
Run Code Online (Sandbox Code Playgroud)