I am trying to parse configuration INI files in Linux.
I would like to use Boost and someone pointed me the program options
library.
The thing is that I can read lines having the syntax field=value
, but how to deal with different 开发者_开发技巧sections i.e. lines having [Section_Name]
in it?
With the code below I have always an exception
Below the code I tried. Thanks AFG
const char* testFileName = "file.ini";
std::ifstream s;
s.open( testFileName );
namespace pod = boost::program_options::detail;
std::set<std::string> options;
options.insert("a");
options.insert("b");
options.insert("c");
//parser
for (pod::config_file_iterator i(s, options), e ; i != e; ++i)
{
std::cout << i->value[0] << std::endl;
}
I'm using parse_config_file
from program_options, so it may be different, but there the name of the option is SectionName.name
if you have something like name=value
in [SectionName]
.
std::string config_filename = "foo.ini";
namespace po = boost::program_options;
po::options_description my_options("Options");
int my_opt;
my_options.add_options()
("SectionName.my_opt", po::value(&my_opt)->default_value(64), "My option");
std::ifstream config_stream(config_filename.c_str());
po::variables_map vm;
po::store(po::parse_config_file(config_stream, my_options), vm);
po::notify(vm);
// value is now in my_opt, also accessible by vm["SectionName.my_opt"].as<int>()
As stated earlier by etarion, the identifier of the option must be prefixed by their enclosing section. Here is a simple modification on your code to demonstrate :
int main()
{
std::stringstream s(
"[Test]\n"
"a = 1\n"
"b = 2\n"
"c = test option\n");
std::set<std::string> options;
options.insert("Test.a");
options.insert("Test.b");
options.insert("Test.c");
for (boost::program_options::detail::config_file_iterator i(s, options), e ; i != e; ++i)
std::cout << i->value[0] << std::endl;
}
This program outputs :
1
2
test option
精彩评论