Wednesday, August 22, 2007

How to parse *.ini files with boost

I've spend some time to explore how to use "config_file_iterator" from boost::program_options library. Here is example:
---  config_test.cpp  ---
// Snippet 1: Boost config file parsing
//
#include <iostream>
#include <string>
#include <set>
#include <sstream>

#include <boost/config.hpp>
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>

namespace pod = boost::program_options::detail;

int main()
{
//contents
std::stringstream s(
"a = 1\n"
"b = 2\n"
"c = test option\n");
//parameters
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;
}
}
------------------




And more detailed sample:
#include <iostream>
#include <string>
#include <set>
#include <sstream>
#include <exception>
#include <fstream>

#include <boost/config.hpp>
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>

namespace pod = boost::program_options::detail;

int main()
{
std::ifstream config("manager.ini");
if(!config)
{
std::cerr<<"error"<<std::endl;
return 1;
}

//parameters
std::set<std::string> options;
std::map<std::string, std::string> parameters;
options.insert("*");

try
{
for (pod::config_file_iterator i(config, options), e ; i != e; ++i)
{
std::cout << i->string_key <<" "<<i->value[0] << std::endl;
parameters[i->string_key] = i->value[0];
}
std::cout << parameters["StatLogServer.Path"] << std::endl;
}
catch(std::exception& e)
{
std::cerr<<"Exception: "<<e.what()<<std::endl;
}
}

5 comments:

VictoryIsMine said...

This is awesome

Thanks

Magno Cardona Heck said...

CC=/usr/local/bin/g++

BOOSTINCLUDE = your boost include
BOOSTLIB = your boost lib

I compiled boost with gcc 3.4.6

for your exmaple I had to to add the includes then link to boost libs

and added
-lboost_program_options-gcc34-mt

depending your compiler 34 my 3.4.6
ufff ..

$(CC) -I $(BOOSTINCLUDE) example.cpp -o example -L$(BOOSTLIB) -lboost_program_options-gcc34-mt

simon said...

It is cool staff. I am newbie to Boost library, this example read value from configuration file. Do yo9u have example how to write/change values?

Krishna said...

Thanks for your example.....it helped mee.......

La Muerte Peluda said...

Thank you very much! More flexible than Boost Tutorials!