voiko
voiko

Reputation: 43

c++ boost parse ini file when containing multikeys

I need to parse ini file using C++ with boost library. This file contains the multi keys. For example,

[section_1]
key_1=value_1
key_1=value_2
...
key_n=value_n
[section_2]
key1=value_1
key1=value_2
...
key_n=value_1
key_n=value_2
[]
...
[section_n]
...

I tried use the functional of boost library: the function boost::property_tree::ini_parser::read_ini(), but it can't contain the multikey in ini file and return the exception. So I tried use the function boost::program_options::parse_config_file(), but it's not what I need.

What functionality should I use to parse the ini file and for each section I can to get own structure with relevant key values?

Upvotes: 4

Views: 1918

Answers (2)

sehe
sehe

Reputation: 393249

Your input is simply not an INI file, as INI files do not permit duplicate values. You can write your own parser, e.g. using the code I wrote here:¹

If you replace the section_t map

typedef std::map<textnode_t, textnode_t>    section_t;

with multimap:

typedef std::multimap<textnode_t, textnode_t>    section_t;

you can parse repeated keys:

[section_1]
key_1=value_1
key_1=value_2
key_n=value_n
[section_2]
key1=value_1
key2=value_2
key_n=value_1
key_n=value_2
[section_n]

See full code here: https://gist.github.com/sehe/068b1ae81547b98a3cec02a530f220df

¹ or Learning Boost.Spirit: parsing INI and http://coliru.stacked-crooked.com/view?id=cd1d516ae0b19bd6f9af1e3f1b132211-0d2159870a1c6cb0cd1457b292b97230 and possibly others

Upvotes: 1

sehe
sehe

Reputation: 393249

A SSCCE that might help you

Live On Coliru

#include <boost/property_tree/ini_parser.hpp>
#include <iostream>
using boost::property_tree::ptree;

int main() {
    std::istringstream iss(R"([section_1]
key_1=value_1
key_2=value_2
key_n=value_n
[section_2]
key1=value_1
key2=value_2
key_n=value_n
key_m=value_m
[]
[section_n])");

    ptree pt;
    read_ini(iss, pt);

    for (auto& section : pt) {
        std::cout << "[" << section.first << "]\n";
        for (auto& key : section.second) {
            std::cout << key.first << "=" << key.second.get_value("") << "\n";
        }
    }
}

Prints

[section_1]
key_1=value_1
key_2=value_2
key_n=value_n
[section_2]
key1=value_1
key2=value_2
key_n=value_n
key_m=value_m

Upvotes: 0

Related Questions