Saturday, September 19, 2009

EasyConfig C++ Class

Hey all, I just wanted to share with you a class I made that is kinda useful when you want to manipulate the Config files such as *.ini.

You'll see it's not hard at all to use it.

Please note that there are 2 constructors, an empty one that doesn't require any argument and another one that takes the file name.
->If you declare an object without any file name, you'll have to use the SetFileName method.

Here's an exemple :
#include "stdafx.h"
using namespace std;

int main(int argc, char* argv[])
{
ConfigFile myIni;

myIni.SetFileName("C:\\Hax.txt");

cout << myIni.ReadStringValue("LOL", "value1").c_str() << endl;

    cout << "Writing int into value2..." << endl;

    myIni.WriteValue("LOL", "value2", 1337);
    cout << myIni.ReadIntValue("LOL", "value2") << endl;

    cout << "Writing float into value3..." << endl;

    myIni.WriteValue("LOL", "value3", 3.14f);
    cout << myIni.ReadFloatValue("LOL", "value3") << endl;

    return 0;
}
WriteValue is an overloaded function that works with float, int and strings which is actually what I needed. The code launches a ConfigFileException when shit happens. For exemple :
ConfigFile myIni;

cout << myIni.ReadStringValue("LOL", "value1").c_str() << endl;
In this code, we didn't set a file name. The code will launch an exception that contains : - The file name (In this case, it's ) - And the error description To avoid unhandled exceptions :
ConfigFile myIni;

try
{
cout << myIni.ReadStringValue("LOL", "value1").c_str() << endl;
}
catch( ConfigFileException e )
{
cout << "*** EXCEPTION CAUGHT ***"<< endl;
cout << e.fileName << endl;
cout << e.errMessage<< endl;
}
I added the exceptions stuff today, so if you find anything i could add/correct, just say =) And now, the file you're all waiting for : EasyCfg.cpp
Alright, if you liked this don't forget the credits if you'd like to use it. A 'thank you' never killed anybody ;)

No comments:

Post a Comment