2009年11月20日 星期五

Glib (1) Key-value file parser

Glib中有個功能,Key-value file parser 是用來讀取你一個設定檔,如一般常看到的.ini or .conf ,運用glib 可以很容易分析出所設定的參數。用一個小程式來了解如何運用這項功能:
demo file: keyfile.c myconf.ini


keyfile.c

#include <stdio.h>
#include <glib.h>

typedef struct
{
gchar **prod;
gint *price;
} GOODS;

int main()
{
GOODS *conf;
GKeyFile *keyfile;
GKeyFileFlags flags;
GError *error = NULL;
int channel;
double freq;
gsize length;
int i;

// Create a new GKeyFile object and a bitwise list of flags.
keyfile = g_key_file_new();
flags = G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS;

// Load the GKeyFile from keyfile.conf or return.
if (!g_key_file_load_from_file (keyfile, "myconf.ini", flags, &error))
return 0;

printf("[doc]\n");
printf("value: %d\n", g_key_file_get_integer(keyfile, "doc", "value", NULL));
printf("version: %s\n", g_key_file_get_string(keyfile, "doc", "version", NULL));

printf("\n[TV]\n");
if (g_key_file_get_boolean(keyfile, "tv", "on", NULL))
printf("TV: true\n");
else
printf("TV: true\n");
channel=g_key_file_get_integer(keyfile, "tv", "channel", NULL);
freq=g_key_file_get_double(keyfile, "tv", "Hz", NULL);
printf("TV: %d\n", channel);
printf("TV: %f\n",freq);

/* Create a new Settings object. If you are using GTK+ 2.8 or below, you should use g_new() or g_malloc() instead! */
conf = g_slice_new (GOODS);

conf->prod = g_key_file_get_string_list(keyfile, "LIST","prod_list", &length, NULL);
conf->price= g_key_file_get_integer_list(keyfile, "LIST","price_list", &length, NULL);

printf("\n[LIST]\n");
printf("name: ");
for(i=0;i printf("%s ",conf->prod[i]);

printf("\nprice: ");
for(i=0;i printf("%d ",conf->price[i]);

printf("\n");

return 0;
}



myconf.ini



# This is a example

[doc]
value=66
version=2.6.17

[tv]
on=yes
channel=23
Hz=59.6

[LIST]
prod_list=book;coffee;pen
price_list=23;54;3


接下來編譯:


[root@ecken02 glib]# arm-linux-gcc -Wall -static `arm-linux-pkg-config --cflags --libs glib-2.0` -o keyfile keyfile.c -lglib-2.0 -liconv -lintl

移到版子上執行
sh-3.2# ./keyfile
[doc]
value: 66
version: 2.6.17

[TV]
TV: true
TV: 23
TV: 59.600000

[LIST]
name: book coffee pen
price: 23 54 3
sh-3.2#


它已經將設定檔的值讀出來了,不過感覺執行的速度有點慢....

sh-3.2# ls -l
-rwxrw-r-- 1 root root 152 Nov 9 2009 Makefile
-rwxr-xr-x 1 root root 2304376 Nov 23 2009 keyfile
-rwxrw-r-- 1 root root 1641 Nov 9 2009 keyfile.c
-rwxrw-r-- 1 root root 136 Nov 9 2009 myconf.ini
sh-3.2#

天啊 !! 想不到執行檔要2.3M,真是不符合軟體短小精幹的要求。
再去掉不必要的symbol,

sh-3.2# ls -l
-rwxrw-r-- 1 root root 152 Nov 9 2009 Makefile
-rwxr-xr-x 1 root root 1363192 Nov 23 2009 keyfile
-rwxrw-r-- 1 root root 1641 Nov 9 2009 keyfile.c
-rwxrw-r-- 1 root root 136 Nov 9 2009 myconf.ini
sh-3.2#

還有1.3M,差不多就只能這樣了。

沒有留言: