解析类似 INI 的配置文件
我正在编写一个类似 INI 的配置文件,我想知道在 C/C++ 中解析它的最佳方法。我在 POSIX 上编写它,所以我将使用 # 而不是 ;。这并不重要。我只是想知道,是否有某种关于解析事物的教程、文章或其他东西。
I'm writing an INI-like configuration file and I want to know the best way to parse it in C/C++. I'm writing it on POSIX, so I'll be using # instead of ;. Which doesn't matter. I just want to know, is there some kind of tutorial, article on parsing things or something.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
有很多关于解析的教程和文章,但是您所处理的内容是如此微不足道,以至于大多数可能都是多余的。
考虑到以前这样做的频率,我会从 查看一些已经实现了几乎您想要的功能的现有代码。
There are lots of tutorials and articles on parsing, but what you're dealing with is so trivial that most of them will probably be overkill.
Given how often this has been done before, I'd start by looking at some of the existing code that already implements almost what you want.
已经有很多开源库,您可能只需很少的修改或无需修改即可使用,例如 libini。
There are plenty of open source libraries out there already which you can probably use with little or no modification, e.g. libini.
正如 C++ 基本内容中常见的那样,boost 有一个可以读取 ini 文件的库。事实上,有两个库,具体取决于您想要实现的目标:
As often in C++ basic stuffs, boost have a library that can read ini files. In fact there is two libs, depending on what you want to achieve :
尝试配置器。它是易于使用且灵活的 C++ 库,用于配置文件解析(从最简单的 INI 到具有任意嵌套和语义检查的复杂文件)。仅标头且跨平台。使用 Boost C++ 库。
请参阅:http://opensource.dshevchenko.biz/configurator
Try Configurator. It's easy-to-use and flexible C++ library for configuration file parsing (from simplest INI to complex files with arbitrary nesting and semantic checking). Header-only and cross-platform. Uses Boost C++ libraries.
See: http://opensource.dshevchenko.biz/configurator
根据您实际需要的复杂程度,您可能只需在循环中使用 fgets() 并手动解析每一行(例如使用 strstr()、strchr()、strcmp() 等)。如果您只需要获取一些值,那么拖动解析库就没有什么意义。
Depending on how much complexity you actually need, you might get away with just using fgets() in a loop, and parsing each line manually (e.g. with strstr(), strchr(), strcmp(), etc). There's little point in dragging in a parsing library if you're just going to need to grab a few values.
如果 Boost 对您来说太过分了,请尝试这个 6 Kb BSD 许可的代码。
“inih(INI Not Invented Here)是一个用 C 语言编写的简单 .INI 文件解析器。它只有几页代码,并且设计得小而简单,因此非常适合嵌入式系统。”
http://code.google.com/p/inih/
还有一个 C++ 类,如果你喜欢对象,它支持“;”和“#”评论。
If Boost is an overkill for you, try this 6 Kb BSD-licensed code.
"inih (INI Not Invented Here) is a simple .INI file parser written in C. It's only a couple of pages of code, and it was designed to be small and simple, so it's good for embedded systems."
http://code.google.com/p/inih/
There's also a C++ class, if you prefer objects, and it supports both ";" and "#" comments.