2010年1月21日

GLib Key-value file parser

// test_KeyFile.c
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>

int main(void) {
char* filename = "/usr/share/applications/gnome-terminal.desktop";
GError* error = NULL;
gsize length = 0;

GKeyFileFlags flags = G_KEY_FILE_NONE;
GKeyFile* keyFile = g_key_file_new();

if(!g_key_file_load_from_file(keyFile, filename, flags, &error)) {
g_key_file_free(keyFile);
g_printerr("File name: %s, %s\n", filename, error->message);
return EXIT_FAILURE;
}

gchar** groups = g_key_file_get_groups(keyFile, &length);
int i;
for (i = 0; i < length; ++i) {
gchar* group_name = groups[i];
g_print("Group name: %s\n", group_name);

gsize keyLength = 0;
gchar** keys = g_key_file_get_keys(keyFile, group_name, &keyLength, &error);
int j;
for (j = 0; j < keyLength; ++j) {
gchar* key = keys[j];
gchar* value = g_key_file_get_string(keyFile, group_name, key , &error);
g_print("%s,\t%s\n", key, value);
g_free(value);
}
g_strfreev(keys);
}
g_strfreev(groups);
g_key_file_free(keyFile);
puts("EXIT");
return EXIT_SUCCESS;
}
/*
$ gcc `pkg-config --cflags --libs glib-2.0` -o test_KeyFile test_KeyFile.c
$ ./test_KeyFile
Group name: Desktop Entry
Name, Terminal
Comment, Use the command line
TryExec, gnome-terminal
Exec, gnome-terminal
Icon, utilities-terminal
Type, Application
X-GNOME-DocPath, gnome-terminal/index.html
X-GNOME-Bugzilla-Bugzilla, GNOME
X-GNOME-Bugzilla-Product, gnome-terminal
X-GNOME-Bugzilla-Component, BugBuddyBugs
X-GNOME-Bugzilla-Version, 2.28.1
Categories, GNOME;GTK;Utility;TerminalEmulator;
StartupNotify, true
OnlyShowIn, GNOME;
X-Ubuntu-Gettext-Domain, gnome-terminal
EXIT
*/

沒有留言:

網誌存檔