How to parse ini file with Boost

Marcus Barnet picture Marcus Barnet · May 30, 2011 · Viewed 67.3k times · Source

I have a ini file which contains some sample values like:

[Section1]
Value1 = 10
Value2 = a_text_string

I'm trying to load these values and print them in my application with Boost but I don't understand how to do this in C++.

I searched in this forum in order to find some examples (I always used C and so I'm not very good in C++) but I found only examples about how to read values from file all at once.

I need to load just a single value when I want, like string = Section1.Value2 because I don't need to read all the values, but just few of them.

I'd like to load single values and to store them in variable in order to use them when I want in my application.

It is possible to do this with Boost?

At the moment, I'm using this code:

#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 s("file.ini");
    if(!s)
    {
        std::cerr<<"error"<<std::endl;
        return 1;
    }

    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;
   }

But this just read all the values in a for loop; at the contrary I just want to read single values when I want and I don't need to insert values in the file, because it is already written with all the values which I need in my program.

Answer

Timo picture Timo · May 30, 2011

You can also use Boost.PropertyTree to read .ini files:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>

...

boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini("config.ini", pt);
std::cout << pt.get<std::string>("Section1.Value1") << std::endl;
std::cout << pt.get<std::string>("Section1.Value2") << std::endl;