Tuesday, May 28, 2013

C - Key/Value Pair Programming

/* conf.txt a=1 b=2 c=3 x=4 y=5 z=6 */ #include <stdio.h> #include <stdlib.h> #include <string.h> struct { char *a; int b; char *c; int x; char *y; int z; } conf; struct config_t { char *key; enum { TYPE_STR, TYPE_INT, } value_type; union { char **str_var; int *int_var; }; } config_table[] = { {"a", TYPE_STR, {.str_var=&conf.a} }, {"b", TYPE_INT, {.int_var=&conf.b}}, {"c", TYPE_STR, {.str_var=&conf.c}}, {"x", TYPE_INT, {.int_var=&conf.x}}, {"y", TYPE_STR, {.str_var=&conf.y}}, {"z", TYPE_INT, {.int_var=&conf.z}}, {NULL, TYPE_STR, {NULL} } }; int main(int argc, char *argv[]) { char buf[80]; FILE *fp; struct config_t *pConfig; char *k, *v, *found; fp=fopen("conf.txt", "r"); if ( !fp ) { perror("fopen failed"); exit(1); } while ( fgets(buf, sizeof(buf), fp)!=NULL ) { found=strchr(buf, '\n'); if ( found ) { *found=0x00; } found = strchr(buf, '='); if ( !found ) { continue; } *found=0x00; k=buf; v=found+1; pConfig = config_table; for (; pConfig->key ; ++pConfig) { if ( strcmp(k, pConfig->key)==0 ) { if ( pConfig->value_type==TYPE_STR ) { *pConfig->str_var = strdup(v); } else if ( pConfig->value_type==TYPE_INT ) { *pConfig->int_var = atoi(v); } } } } printf("a:%s\nb:%d\nc:%s\n", conf.a, conf.b, conf.c); printf("x:%d\ny:%s\nz:%d\n", conf.x, conf.y, conf.z); return 0; }

No comments: