配置文件格式:
每一行有两种格式:
1. #注释
2. key value #注释
例如:
#此文件是配置项文件,主要控制主程序的部分变量。
history 1 #测试1
name 2
big 3 #测试2
解析逻辑:
1.以一行为单位,当遇到\n时将当前数据输出出来
2. 遇到#,直接将其数据输出出来,直接读到行某。
3. 利用falge 来区别Key和Value
代码如下:
复用时,可以创建结构体将结构体放入队列或其它结构中用于访问。
#include<conf.h>#define ConfName "conf.conf"void readConf(QueP* nowP){FILE* fp;char* nowLine;fp=fopen(ConfName,"r");char nowC;int flage=0;char nowKey[200];int keyIndex=0;char nowValue[200];int valueIndex=0;memset(nowKey,0x00,200);memset(nowValue,0x00,200);while((nowC=getc(fp))!=EOF){if(nowC==' '){continue;}if(nowC=='#'){while((nowC=getc(fp))!='\n'){continue;}if(strcmp(nowKey,"")){printf("nowKey is %s,nowValue is %s\n",nowKey,nowValue);}flage=0;memset(nowKey,0x00,200);keyIndex=0;memset(nowValue,0x00,200);valueIndex=0;continue;}if(nowC=='\n'){if(strcmp(nowKey,"")){printf("nowKey is %s,nowValue is %s\n",nowKey,nowValue);}flage=0;memset(nowKey,0x00,200);keyIndex=0;memset(nowValue,0x00,200);valueIndex=0;continue;}if(nowC!=' '&&flage==0){do{nowKey[keyIndex]=nowC;keyIndex+=1;}while((nowC=getc(fp))!=' ');flage+=1;continue;}if(nowC!=' '&&flage==1){nowValue[valueIndex]=nowC;valueIndex+=1;continue;}}
}
以上示例输出结果如下:
$ ./readCon.exe
nowKey is history,nowValue is 1
nowKey is name,nowValue is 2
nowKey is big,nowValue is 3