INI Parser using Flex and Bison in C++

This is a follow-up to my previous posting about using Flex and Bison together in C++ mode. This new example actually does something useful: parses an INI file and gives easy access to the values. Just like the last example, this is not a tutorial. Download the source code and give it a read – I tried to make it as straightforward as possible.

Download the source code.

This example uses the parser and the scanner to extract data from a stream into data structures. Once the stream has been parsed, there is no more need for the parser / scanner. Instead of having them as member variables of the class, they have been moved to local variables in the function that parses the stream so that we aren’t wasting memory keeping those class instances in memory when they no longer serve a purpose.

This example also keeps track of locations using the yylloc variable so we can tell where an error occurs. If an error occurs, an exception (of type std::string) is thrown that says what the error is and where it occured (line number, character number).

The Makefile for this example is greatly improved; builds are now incremental (files that have not changed are not recompiled).

I am NOT an expert on Bison, Flex, C++, Makefiles, etc. and have coded this as a learning experience. It is provided in the hopes that others will be able to learn from it. If you notice anything that can be improved on, please leave a comment so that other visitors as well as myself can benefit. This code is provided under the WTFPL license with no warranty.

Did you find this article useful? Pass it on!
  1. Peter Griffin

    Hi thanks for sharing this nice example, i am quite a novice when it comes to c++ programming and i was hoping you could explain to me what changes i’d need to make to your example to call a member method of IniFile instead of putting the data into the map.

    Thanks alot,
    Peter

Leave a Comment

Trackbacks and Pingbacks: