我的任务很简单——我只需要解析这样的文件:
Apple = 1
Orange = 2
XYZ = 3950
但我不知道可用 key 集。我使用 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 解析器之前:
它支持注释(单行和 block )、引号、转义等。
(作为奖励,它可选择记录所有已解析元素的确切源位置,这是该问题的主题)。
不过,为了您的目的,我想我会推荐 Boost Property Tree。
关于c++ - 在 C++ 上迭代 ini 文件,可能使用 boost::property_tree::ptree?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16135285/