如何用Boostparsingini文件

我有一个ini文件,其中包含一些示例值,如:

[Section1] Value1 = 10 Value2 = a_text_string 

我试图加载这些值,并用Boost在我的应用程序中打印它们,但我不明白如何在C ++中执行此操作。

我在这个论坛search,以find一些例子(我总是使用C,所以我不是很好的C + +),但我只发现如何从文件一次读取值的例子。

我需要加载一个单一的值,如string = Section1.Value2因为我不需要读取所有的值,但只是less数。

我想加载单个值并将其存储在variables中,以便在我的应用程序中使用它们。

Boost可以做到这一点吗?

目前,我正在使用这个代码:

 #include <iostream> #include <string> #include <set> #include <sstream> #include <exception> #include <fstream> #include <boost/config.hpp> #include <boost/program_options/detail/config_file.hpp> #include <boost/program_options/parsers.hpp> namespace pod = boost::program_options::detail; int main() { std::ifstream s("file.ini"); if(!s) { std::cerr<<"error"<<std::endl; return 1; } std::set<std::string> options; options.insert("Test.a"); options.insert("Test.b"); options.insert("Test.c"); for (boost::program_options::detail::config_file_iterator i(s, options), e ; i != e; ++i) std::cout << i->value[0] << std::endl; } 

但是这只是读取for循环中的所有值; 相反,我只想读取单个值,当我需要时,我不需要在文件中插入值,因为它已经写在我的程序中需要的所有值。

您也可以使用Boost.PropertyTree来读取.ini文件:

 #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> ... boost::property_tree::ptree pt; boost::property_tree::ini_parser::read_ini("config.ini", pt); std::cout << pt.get<std::string>("Section1.Value1") << std::endl; std::cout << pt.get<std::string>("Section1.Value2") << std::endl; 

由于其简单的结构,parsingINI文件是容易的。 使用AX我可以写几行来解​​析部分,属性和注释:

 auto trailing_spaces = *space & endl; auto section = '[' & r_alnumstr() & ']'; auto name = +(r_any() - '=' - endl - space); auto value = '"' & *("\\\"" | r_any() - '"') & '"' | *(r_any() - trailing_spaces); auto property = *space & name & *space & '=' & *space & value & trailing_spaces; auto comment = ';' & *(r_any() - endl) & endl; auto ini_file = *comment & *(section & *(prop_line | comment)) & r_end(); 

更详细的例子可以在Reference.pdf中find

关于不读整个文件,可以用不同的方式完成。 首先,INI格式的parsing器至less需要前向迭代器,所以你不能使用stream迭代器,因为它们是input迭代器。 您可以创build一个单独的类与所需的迭代器stream(我写了一个这样的类过去与滑动缓冲区)。 您可以使用内存映射文件。 或者您可以使用dynamic缓冲区,从标准stream读取并提供给parsing器,直到find值。 如果你不想拥有一个真正的parsing器,并且不关心INI文件结构是否正确,那么你可以简单地在文件中search你的记号。 input迭代器就足够了。

最后,我不确定避免阅读整个文件带来的好处。 INI文件通常很小,而且由于硬盘驱动器和多个缓冲系统无论如何都会读取一个或多个扇区(即使只需要一个字节),所以我怀疑部分读取文件会有任何性能改善反复做),可能是相反的。

我已经阅读了一篇关于使用boost方法的INIparsing的好文章,它被称为INI文件读取器,使用 Silviu Simen 的精神库 。

这很简单。

该文件需要被parsing,这必须按顺序进行。 因此,我只是读取整个文件,将所有值存储在某个集合( mapunordered_map ,可能使用pair<section, key>作为键或使用map的映射),并在需要时从中取出它们。