读取配置文件 以#开头的行是注释行 键和值 用空格分开 一行一个键值对
如:
# 注释
key1 2
key2 aab
增加结构体 Config的成员key(自行定义的变量名)存变量, 添加代码
if( strcasecmp(key,"key")==0 ) {
strncpy(sConfig->key,val,128);
}
获取值。
typedef struct { int port; char rootDir[128]; } Config; /** * read config from httpd.conf * parameters : file name * return */ /** * [readCfg read conf key val ] * @param filename [file name ] * @param sConfig [config struct ] */ void readCfg(char *filename, struct Config* sConfig) { FILE *pf = NULL; char buf[2048]; int i = 0,j = 0; char key[128]; char val[128]; pf = fopen(filename, "r+"); if (NULL==pf){ perror("open config file error. use default config."); return; } while(!feof(pf)) { fgets(buf,2048,pf); i = 0; j = 0; printf("%s ", buf); // get key while (!isspace(buf[i]) && (i < strlen(buf) - 1)) { key[j] = buf[i]; i++; j++; } key[j] = 0; printf("%s ", key); if ('#'==key[0]) continue; // get val i++; j=0; while (!isspace(buf[i]) && (i < strlen(buf) - 1)) { val[j] = buf[i]; i++; j++; } val[j] = 0; printf("%s ", val); if( stricmp(key,"port")==0 ) { sConfig->port = atoi(val); } if( stricmp(key,"rootDir")==0 ) { strncpy(sConfig->rootDir,val,128); } } fclose(pf); }