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

前端 未结 2 2252
执念已碎
执念已碎 2021-02-10 16:09

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

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-10 16:29

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

    #include 
    #include 
    
    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() << "\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.

提交回复
热议问题