遍历对C ++的ini文件,可能是使用boost :: property_tree :: ptree中? [英] iterate over ini file on c++, probably using boost::property_tree::ptree?

查看:1316
本文介绍了遍历对C ++的ini文件,可能是使用boost :: property_tree :: ptree中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是微不足道的 - 我只是需要解析这样的文件:

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

Apple = 1
Orange = 2
XYZ = 3950

但我不知道一组可用密钥。我是比较解析这个文件很容易使用C#,让我演示源$ C ​​$ C:

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

现在我只是需要用C ++做同样的事情。我想用的boost :: property_tree :: ptree中不过似乎我只是不能超过ini文件迭代。这很容易读取ini文件:

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

但它是不可能的遍历它,请参阅该问题<一href=\"http://stackoverflow.com/questions/11065938/boost-program-options-get-all-entries-in-section\">Boost方案选择 - 获得部分所有条目

现在的问题是 - 什么是写C#code的模拟上面C上的最简单的方法++

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

推荐答案

要直接回答你的问题:当然的迭代一个属性树是可能。事实上,它是微不足道的:

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

这导致像输出:

[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


我已经写了使用的升压精神前:

  • 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.

这篇关于遍历对C ++的ini文件,可能是使用boost :: property_tree :: ptree中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆