Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate over ini file on c++, probably using boost::property_tree::ptree?

Tags:

c++

boost

My task is trivial - i just need to parse such file:

Apple = 1
Orange = 2
XYZ = 3950

But i do not know the set of available keys. I was parsing this file relatively easy using C#, let me demonstrate source code:

    public static Dictionary<string, string> ReadParametersFromFile(string path)
    {
        string[] linesDirty = File.ReadAllLines(path);
        string[] lines = linesDirty.Where(
            str => !String.IsNullOrWhiteSpace(str) && !str.StartsWith("//")).ToArray();

        var dict = lines.Select(s => s.Split(new char[] { '=' }))
                        .ToDictionary(s => s[0].Trim(), s => s[1].Trim());
        return dict;
    }

Now I just need to do the same thing using c++. I was thinking to use boost::property_tree::ptree however it seems I just can not iterate over ini file. It's easy to read ini file:

boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini(path, pt);

But it is not possible to iterate over it, refer to this question Boost program options - get all entries in section

The question is - what is the easiest way to write analog of C# code above on C++ ?

like image 251
Oleg Vazhnev Avatar asked Dec 01 '22 21:12

Oleg Vazhnev


1 Answers

To answer your question directly: of course iterating a property tree is possible. In fact it's trivial:

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

int main()
{
    using boost::property_tree::ptree;
    ptree pt;

    read_ini("input.txt", pt);

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

This results in output like:

[Cat1]
name1=100 #skipped
name2=200 \#not \\skipped
name3=dhfj dhjgfd
[Cat_2]
UsagePage=9
Usage=19
Offset=0x1204
[Cat_3]
UsagePage=12
Usage=39
Offset=0x12304

I've written a very full-featured Inifile parser using boost-spirit before:

  • Cross-platform way to get line number of an INI file where given option was found

It supports comments (single line and block), quotes, escapes etc.

(as a bonus, it optionally records the exact source locations of all the parsed elements, which was the subject of that question).

For your purpose, though, I think I'd recomment Boost Property Tree.

like image 66
sehe Avatar answered Dec 03 '22 10:12

sehe