加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

迭代c上的ini文件,可能使用boost :: property_tree :: ptree?

发布时间:2020-12-16 10:40:36 所属栏目:百科 来源:网络整理
导读:我的任务很简单 – 我只需要解析这样的文件: Apple = 1Orange = 2XYZ = 3950 但我不知道可用密钥的集合.我使用C#解析这个文件比较容易,让我演示源代码: public static Dictionarystring,string ReadParametersFromFile(string path) { string[] linesDirty
我的任务很简单 – 我只需要解析这样的文件:

Apple = 1
Orange = 2
XYZ = 3950

但我不知道可用密钥的集合.我使用C#解析这个文件比较容易,让我演示源代码:

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文件:

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

但是不可能迭代它,请参考这个问题Boost program options – get all entries in section

问题是 – 在C上编写C#代码模拟的最简单方法是什么?

解决方法

直接回答您的问题:当然可以迭代属性树.事实上它是微不足道的:

#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

我之前使用boost-spirit编写了一个非常全功能的Inifile解析器:

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

它支持注释(单行和块),引号,转义等.

(作为奖励,它可选地记录所有已解析元素的确切源位置,这是该问题的主题).

不过,为了您的目的,我想我会推荐Boost Property Tree.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读