Click here to Skip to main content
15,884,099 members
Articles / Programming Languages / C
Article

A C++ Config File Parser

Rate me:
Please Sign up or sign in to vote.
4.23/5 (14 votes)
16 May 2008LGPL31 min read 157.2K   3.7K   47   20
An STL based C++ utility class to parse structured config files.

Introduction

This article describes a small, light-weight parser for structured config files. Unlike INI-Files, config files may be sub-structured arbitrarily deep. Config files support the expansion of symbolic values from previously defined variables and environment variables.

Using the code

Basic usage

Consider the following example config file:

# Environment variables used as expansion symbol
# Note: symbol names are case sensitive
tempFolder = %TEMP%

# already defined variables used as expansion symbol
tempSubFolder = %tempFolder%\config-demo

Parsing is as simple as:

C++
Config config("demo.config", envp);

cout << "tempFolder    = '"
   << config.pString("tempFolder") << "'" << endl;
cout << "tempSubFolder = '"
   << config.pString("tempSubFolder") << "'" << endl;

pString() retrieves an unparsed std::string value. The class Config provides additional methods which try to parse the value as a boolean, double, or int.

Config sub groups

Config files may contain sub-groups, as shown in the following example:

# Sub group example
baseName = Welcome Note
message1 = (
#  strings may use ""; it does not make a difference, however.
   name = "%baseName% 1"
   text = Sample message text
)

message2 = (
   name = %baseName% II
   text = Another sample message text
)

Unlike traditional INI-Files, sub-groups may contain further sub-groups up to an arbitrary depth. A sub-group may be accessed by name, or the whole collection of sub-groups may be accessed as stl::map<string, Config*>&.

The following code shows how to parse all sub-groups starting with a prefix, without knowing the exact count in advance:

C++
// get properties for all subgroups starting with prefix
map<string, Config*> messages = config.getGroups(); // all groups
const string messagePrefix = "message"; // prefix for group name
for (map<string, Config*>::iterator i = messages.begin(); i != messages.
end(); ++i) {
       string groupName = i->first;
       Config* group = i->second;

       // test group name for prefix
       if (groupName.substr(0, messagePrefix.length()) == messagePrefix) {
           // display group contents
           cout << group->pString("name") << ":" << endl;
           cout << "   " << group->pString("text") << endl;
       }
}

With this feature, the parser may be also used for structured input documents other than config files. Unlike XML, the representation is more compact, parsing is simpler, and variable expansion is already included.

The distributed source contains very simple error handling. Warnings and error messages are logged to the console. On severe error, the process is aborted. Integrating the source in a project, one may consider to change this to C++ exception handling, if needed.

Only standard C++ functionality is used, so this code is truly cross platform. MSVS Express 2005 project files are included; manual build was tested successfully with GNU g++/Linux, using:

g++ -o ../configDemo *.cpp

History

  • First release.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 2 Pin
kamelkom22-Jul-11 4:00
kamelkom22-Jul-11 4:00 
JokeNot a joke Pin
Member 74021665-Apr-11 22:28
Member 74021665-Apr-11 22:28 
GeneralThanks... Pin
Member 766349510-Mar-11 0:45
Member 766349510-Mar-11 0:45 
GeneralSmall bug Pin
Shaun Rust30-Mar-10 3:33
Shaun Rust30-Mar-10 3:33 
GeneralUNICODE support would be nice Pin
Jens Grünewald5-Oct-09 4:28
Jens Grünewald5-Oct-09 4:28 
GeneralRock On! Pin
Martin Chapman4-Sep-09 18:57
Martin Chapman4-Sep-09 18:57 
GeneralError Pin
Sb4s1-Sep-09 10:55
Sb4s1-Sep-09 10:55 
GeneralConfig File parser with this file Pin
Deni Lad10-Aug-09 12:11
Deni Lad10-Aug-09 12:11 
I have files like this format:
Test.conf
__________
# test config file:
; any line starting with a non-alphanumeric character is a comment line
! therefore any common comment character is acceptable
/* including c-style comments */
// or C++ style comments


USER=joe # you get everything on this line
NAME = "Bobby Magee" # this is a comment
AGE = 15 // comment as well
POCKETS = (left="string",right="keys",back="wallet") anything here is ignored
VALUES = (5,10,15,20,25,30,35,40) same with this
NESTED = (5,10,15,(20,25),30,35,40) ... and this
NAMES = ("joe", "john", "jeff", "jack", "jay") ; and this
ENABLED = Yes !woo!


Output:
________

INTEGER: AGE = 15 data=(15)
BOOLEAN: ENABLED = True
STRING: NAME = Bobby Magee
ARRAY: NAMES = (
STRING: 0 = joe
STRING: 1 = john
STRING: 2 = jeff
STRING: 3 = jack
STRING: 4 = jay
)
ARRAY: NESTED = (
INTEGER: 0 = 5 data=(5)
INTEGER: 1 = 10 data=(10)
INTEGER: 2 = 15 data=(15)
ARRAY: 3 = (
INTEGER: 0 = 20 data=(20)
INTEGER: 1 = 25 data=(25)
)
INTEGER: 4 = 30 data=(30)
INTEGER: 5 = 35 data=(35)
INTEGER: 6 = 40 data=(40)
)
ARRAY: POCKETS = (
STRING: BACK = wallet
STRING: LEFT = string
STRING: RIGHT = keys
)
STRING: USER = joe # you get everything on this line
ARRAY: VALUES = (
INTEGER: 0 = 5 data=(5)
INTEGER: 1 = 10 data=(10)
INTEGER: 2 = 15 data=(15)
INTEGER: 3 = 20 data=(20)
INTEGER: 4 = 25 data=(25)
INTEGER: 5 = 30 data=(30)
INTEGER: 6 = 35 data=(35)
INTEGER: 7 = 40 data=(40)
)


and header file config.h:
--------------------------
#ifndef __CONFIG_H

#define __CONFIG_H 1

// Flexible configuration file parser class.
// Written by Derek Snider (c)2007 Hostopia.com Inc


typedef enum { cSTR, cINT, cBOOL, cARR } confdat_t;

namespace Config
{

class Datum
{
public:
confdat_t type;
string data;
int64_t value;
map<string, Datum> array;
Datum(istream &);
Datum() { type = cSTR; data = ""; value = 0; }
void dump(const string &key);
};

class File
{
private:
string file;
public:
map<string, Datum> data;
File(const char *); // (constructor reads config file)
const char *get(const char *key) { return data[key].data.c_str(); } // get string
int64_t geti(const char *key) { return data[key].value; } // get integer
bool getb(const char *key) { return data[key].value ? true : false; }// get boolean
map<string, Datum> *geta(const char *key) { return &data[key].array; } // get array
};

}

#endif // __CONFIG_H


test.cpp
------------

// Config file parser

#include <stdint.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>

using namespace std;

#include "config.h"


int main()
{
map<string, Config::Datum>::iterator i;
Config::File conf("test.conf");

for ( i = conf.data.begin(); i != conf.data.end(); ++i )
i->second.dump(i->first);
return 0;
}


I have to create config.cpp....How can i?
Questionparsing of configuration file using vc++ Pin
AVIHAR20-Nov-08 18:29
AVIHAR20-Nov-08 18:29 
Generalwhitespace in config Pin
bbrandin11-Jun-08 2:38
bbrandin11-Jun-08 2:38 
GeneralRe: whitespace in config [modified] Pin
freejack14-Jun-08 19:19
freejack14-Jun-08 19:19 
GeneralRe: whitespace in config Pin
bbrandin15-Jun-08 23:10
bbrandin15-Jun-08 23:10 
GeneralSerialization Pin
Robin22-May-08 16:24
Robin22-May-08 16:24 
GeneralNice work Pin
Laurent Regnier19-May-08 23:38
professionalLaurent Regnier19-May-08 23:38 
GeneralRe: Nice work Pin
freejack23-May-08 22:23
freejack23-May-08 22:23 
Questionwhy not just XML? Pin
Jimmy Zhang17-May-08 20:49
Jimmy Zhang17-May-08 20:49 
AnswerRe: why not just XML? Pin
freejack18-May-08 5:14
freejack18-May-08 5:14 
GeneralRe: why not just XML? Pin
David @ SL20-May-08 1:09
David @ SL20-May-08 1:09 
GeneralRe: why not just XML? Pin
Mike Cravens12-Dec-08 5:51
Mike Cravens12-Dec-08 5:51 
AnswerRe: why not just XML? Pin
Vinod Khare13-Jan-09 11:23
Vinod Khare13-Jan-09 11:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.