开发者

Parsing INI-like configuration files

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 # instea开发者_StackOverflow社区d of ;. Which doesn't matter. I just want to know, is there some kind of tutorial, article on parsing things or something.


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.


There are plenty of open source libraries out there already which you can probably use with little or no modification, e.g. libini.


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 :

  • boost program option allow you to manage program options from command line or from ini or mixed sources : http://www.boost.org/doc/libs/1_44_0/doc/html/program_options.html;
  • boost property tree does the work for you : http://www.boost.org/doc/libs/1_44_0/doc/html/boost_propertytree/parsers.html


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜