It addresses three fundamental problematic issues C users often face:
- Data containers
- Portability
- Utility
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
- ...
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:
Post a Comment