Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost program options - get all entries in section

According to documentation I can parse config files in style :

 [main section]
 string = hello world. 
 [foo]
 message = Hi !

But I need to parse list of plugins :

 [plugins]
 somePlugin. 
 HelloWorldPlugin
 AnotherPlugin
 [settings]
 type = hello world

How can I get vector of strings which are in plugins section ?

like image 680
user1307957 Avatar asked Jun 16 '12 18:06

user1307957


1 Answers

For boost program options config files, if the line is not declaring a section, such as [settings], then it needs to be in a name=value format. For your example, write it as the following:

[plugins]
name = somePlugin
name = HelloWorldPlugin
name = AnotherPlugin
[settings]
type = hello world

The list of plugins will now correspond to the "plugins.name" option, which needs to be a multitoken option.

Below is an example program that reads the above settings from a settings.ini file:

#include <boost/program_options.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main()
{
  namespace po = boost::program_options;

  typedef std::vector< std::string > plugin_names_t;
  plugin_names_t plugin_names;
  std::string settings_type;

  // Setup options.
  po::options_description desc("Options");
  desc.add_options()
    ("plugins.name", po::value< plugin_names_t >( &plugin_names )->multitoken(),
                     "plugin names" )
    ("settings.type", po::value< std::string >( &settings_type ),
                      "settings_type" );

  // Load setting file.
  po::variables_map vm;
  std::ifstream settings_file( "settings.ini" , std::ifstream::in );
  po::store( po::parse_config_file( settings_file , desc ), vm );
  settings_file.close();
  po::notify( vm );    

  // Print settings.
  typedef std::vector< std::string >::iterator iterator;
  for ( plugin_names_t::iterator iterator = plugin_names.begin(),
                                      end = plugin_names.end();
        iterator < end;
        ++iterator )
  {
    std::cout << "plugin.name: " << *iterator << std::endl;
  }
  std::cout << "settings.type: " << settings_type << std::endl;

  return 0;
}

Which produces the following output:

plugin.name: somePlugin
plugin.name: HelloWorldPlugin
plugin.name: AnotherPlugin
settings.type: hello world
like image 156
Tanner Sansbury Avatar answered Oct 05 '22 23:10

Tanner Sansbury