user3030357
user3030357

Reputation: 109

Boost::ini_parser: What is the way to read specific section's values?

I am using boost::property_tree in order to read .ini file.

I know i can read specific key(inside section) -> iniTree.get<std::string>("section.key").

I know i can read all values in the ini file.

I want to read only keys from specific section.

Something like that: iniTree.get<std::vector<std::string> >("section").

Is it possible?

Upvotes: 0

Views: 1339

Answers (1)

sehe
sehe

Reputation: 393174

Yes. You use 'get_child' to get a subtree.

You can use get_child_optional in case you don't know before hand whether the section exists.

Here's a demo that shows both variations:

Live On Coliru

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

using boost::property_tree::ptree;

int main() {

    std::fstream ifs("input.txt");
    ptree pt;

    read_ini(ifs, pt);

    // let's get just the section2

    if (boost::optional<ptree&> oops = pt.get_child_optional("oops")) {
        std::cout << "There is a section `oops`\n";
    } else {
        std::cout << "There is NO section `oops`\n";
    }

    ptree& sub1 = pt.get_child("section2"); // we want the CCs!
    write_ini(std::cout, sub1);
}

And given an input.txt of:

[section1]

huh=value1
slam=value2
cram=value3

[section2]

rabbits=creditcard1
die=creditcard2
eagerly=creditcard3

It'll print the output:

There is NO section `oops`
rabbits=creditcard1
die=creditcard2
eagerly=creditcard3

Upvotes: 2

Related Questions