Created
August 4, 2014 14:27
-
-
Save kyon0304/aad58940ca666e81f5eb to your computer and use it in GitHub Desktop.
read config file use c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "readparam.h" | |
char* delblank( char* str ) | |
{ | |
char* out = str; | |
int i, j; | |
for( i = 0, j = 0; i < strlen( str ); i++,j++ ) | |
{ | |
if( str[i] == ' ' || str[i] == '\n') | |
{ | |
j--; | |
continue; | |
} | |
out[j] = str[i]; | |
} | |
out[j] = '\0'; | |
return out; | |
} | |
Param* find_param( Param* params, char* name ) | |
{ | |
Param* temp; | |
HASH_FIND_STR( params, name, temp ); | |
if( temp == NULL ) | |
{ | |
printf( "wrong key: %s!\n", name ); | |
} | |
return temp; | |
} | |
#if DEBUG | |
int main( int argc, char** argv ) | |
#else | |
Param* read_params( char* fn ) | |
#endif | |
{ | |
FILE* fp; | |
char* line = NULL; | |
size_t len = 0; | |
ssize_t read; | |
char* delim = ";"; | |
char* subdelim = ":"; | |
int count = 0, i = 0; | |
char *str1, *str2, *token, *subtoken; | |
char *saveptr1, *saveptr2; | |
Param* params = NULL; | |
Param* temp = NULL; | |
#if DEBUG | |
char* fn = argv[1]; | |
#endif | |
fp = fopen( fn, "r" ); | |
if ( fp == NULL ) | |
{ | |
return NULL; | |
} | |
Param* s; | |
while( (read = getline( &line, &len, fp )) != -1 ) | |
{ | |
// printf( "remove spaces: %s\n", delblank(line) ); | |
for( count = 1, str1 = delblank(line); ; count++, str1 = NULL ) | |
{ | |
token = strtok_r( str1, delim, &saveptr1 ); | |
if( token == NULL ) | |
break; | |
str2 = token; | |
subtoken = strtok_r( str2, subdelim, &saveptr2 ); | |
if ( subtoken == NULL ) | |
continue; | |
temp = ( Param* ) malloc( sizeof(Param) ); | |
strcpy( temp->name, subtoken ); | |
str2 = NULL; | |
subtoken = strtok_r( str2, subdelim, &saveptr2 ); | |
if ( subtoken == NULL ) | |
continue; | |
temp->value = atoi( subtoken ); | |
HASH_ADD_STR( params, name, temp ); | |
} | |
} | |
for ( s = params; s != NULL; s = s->hh.next ) | |
{ | |
printf( "%s: %d\n", s->name, s->value ); | |
} | |
#if DEBUG | |
printf( "find width's value:%d\n", find_param( params, "width" )->value ); | |
#endif | |
free( line ); | |
fclose( fp ); | |
return params; | |
} | |
void release_params( Param* params ) | |
{ | |
#if DEBUG | |
printf( "release now!\n" ); | |
#endif | |
Param *current, *tmp; | |
if( params == NULL ) | |
{ | |
printf( "empty!\n" ); | |
exit( -1 ); | |
} | |
HASH_ITER(hh, params, current, tmp ) | |
{ | |
HASH_DEL( params, current ); | |
free( current ); | |
current = NULL; | |
} | |
#if DEBUG | |
printf( "release end!\n" ); | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment