Click here to Skip to main content
15,892,269 members
Articles / Programming Languages / C

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.5K   3.7K   47  
An STL based C++ utility class to parse structured config files.
#include <iostream>
using namespace std;

#include "config.h"

int main(int argc, char* argv[], char* envp[])
{
	cout << "config demo program" << endl;
	cout << "(c) 2008 Kai G. Schwebke" << endl;
	cout << "This code is licensed under LGPL and comes with no warranty;" << endl;
	cout << "see COPYING for details." << endl;
	cout << endl;

	// read config file with environment variable expansion support
	Config config("demo.config", envp);
	
	// basic usage of properties
	if (config.pBool("showHello")) {
		int cnt = config.pInt("helloCount");
		string msg = config.pString("helloMessage");
		for (int i = 0; i < cnt; ++i) {
			cout << msg << endl;
		}
		cout << endl;
	}

	// properties with expanded names (no difference in using)
	cout << "tempFolder    = '" << config.pString("tempFolder") << "'" << endl;
	cout << "tempSubFolder = '" << config.pString("tempSubFolder") << "'" << endl;
	cout << endl;

	// 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;
		}
	}

	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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