Ubuntu 10.10 Pentax K-5

Wednesday, May 11, 2005

The wonders of Glib

Glib is a utility for C that makes programming in C must more enjoyable.

It addresses three fundamental problematic issues C users often face:
  • Data containers
  • Portability
  • Utility
Glibs provides safer and stable operations than C, e.g., g_free is much safer than free.
g_new0(num), great than malloc()

Glib provides double-linked-list, single-linked-list, hashtable and so on.
   GList *list = NULL; /* our list pointer */
list = g_list_append(list, "foo1");
list = g_list_append(list, "foo2");

The string operations of glib is also wrapped to be safer ...

  • strcpy->g_strcpy
  • strdup
  • ...
Hash tables, the iterator
Create and destroy hash table
   GHashTable *table;
table = g_hash_table_new(g_str_hash, g_str_equal);
g_hash_table_destroy(table);

Insert and look up data
   FILE *fp;
char buf[1024];

/* just a standard way to open files */
fp = fopen("file.txt", "r");
if(!fp) exit(1); /* if file does not exist, exit */

/* read, file line by line */
while(fgets(buf, sizeof(buf), fp)) {
char *key, *value;
/* get the first and the second field */
key = strtok(buf, "\t");
if(!key) continue;
value = strtok(NULL, "\t");
if(!value) continue;

/* insert into our table */
g_hash_table_insert(table, g_strdup(key), g_strdup(value));
}
fclose(fp);

Some reference

No comments: