Home > C/C++ > Gkeyfile and configuration files

Gkeyfile and configuration files

While looking for a configuration file parser I came across GkeyFile that is part of glib. It was very easy to use and met almost all the requirements that I wanted out of it. Here is a simple howto for GkeyFile…

Key files in GLib are more like .ini files that are mostly available on Windows. The key files data is divided into groups, where the name appears between square bracket characters, and comments are started by the # character. Key files, parsed by GKeyFile can handle strings, localized strings(internationalization support), Boolean values, integers, doubles, and arrays of each of these data types.

A simple example of a KeyFile can be:

#First Group
[Student1]
FirstName= Joe
Age=20

Now in order to get values for FirstName and Age for the group “Student1” you can use the following code in C…

#include <glib.h>

typedef struct
{
gchar *FirstName;
int Age;

} Student;

int main ()
{
Settings *conf;
GKeyFile *keyfile;
GKeyFileFlags flags;
GError *error = NULL;
gsize length;

keyfile = g_key_file_new ();
flags = G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS;

if (!g_key_file_load_from_file (keyfile, “Students.conf”, flags, &error))
{
g_error (error->message);
return -1;
}

conf = g_slice_new (Student);

conf->FirstName = g_key_file_get_string             (keyfile, “Student1”,
“FirstName”, NULL);
conf->Age = g_key_file_get_integer (keyfile, “Student1”,
“Age”, NULL);
return 0;
}

You can find more help for Gekyfile in  Glib Reference Manual

Shoaib Mir
shoaibmir[@]gmail.com

Advertisements
Categories: C/C++ Tags: , ,
  1. interval
    May 12, 2009 at 9:15 am

    How is this different, better, and/or etc. the usual use of the gnome-settings-manager for per-app configuration management in gnome environments? I haven’t found gsm particularly difficult to use and it is the more canonical way to manage settings; it will have to be there if you’re running gnome anyway.

  2. May 12, 2009 at 11:43 am

    For me the scenario was a little different as I had to have it platform independent and make it run on Windows as well, otherwise GSM seems a better option.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: