Linux C实现 读取ini文件项目值的功能---GetIniSectionItem
Linux C实现 读取ini文件项目值的功能---GetIniSectionItem
Linux C实现 读取ini文件项目值的功能---GetIniSectionItem ,以下版本又更新,可以比较正确的读取到各个项的值。- #ifndef INI_FILE_H
- #define INI_FILE_H
- #define NOFILE "nofile"
- #define INIFILE "test.ini"
- #define STRLENMAX 30
- #define ITEMLENMAX 30
- #define LINELENMAX 1024
- #include<string.h>
- char* GetIniSectionItem(char* FileName,char* Section,char* Item)
- {
- char *value,Sect[30],c;
- char linebuf[1024],oldline[1024];
- FILE *inifp;
- int i;
- strcpy(Sect,"[");
- strcat(Sect,Section);
- strcat(Sect,"]");
- /*strcpy(Ite,"[");strcat(Ite,Item);strcat(Ite,"]");*/
- if((inifp=fopen(FileName,"rb"))==NULL)
- {
- return (char*)NOFILE;
- }
- /*printf("Sect = %s,Item = %s /n",Sect,Item);*/
- while((c=fgetc(inifp))!=EOF)
- {
- if(c=='[')
- {
- ungetc(c,inifp);
- fgets(linebuf,1024,inifp);
- if(strstr(linebuf,Sect))
- {
- while((c=fgetc(inifp))!='[' && c!=EOF)
- {
- ungetc(c,inifp);
- fgets(linebuf,1024,inifp);
- if(strstr(linebuf,Item))
- {
- if(value=strchr(linebuf,'='))
- {
- value++;
- /*printf("value = %s /n",value);*/
- fclose(inifp);
- if(*value=='/n')
- return (char *)NULL;
- return value;
- }
- }
- }
- if(c==EOF)
- {
- break;
- }
- ungetc(c,inifp);
- }
- }
- else
- {
- ungetc(c,inifp);
- fgets(linebuf,1024,inifp);
- }
- }
- fclose(inifp);
- return (char*)NULL;
- }
- #endif
以下是以前的版本,存在bug。
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<string.h>
- char* GetIniSectionItem(FILE* fp,char* Section,char* Item)
- {
- char *value;
- char linebuf[1024];
- while(fgets(linebuf,1024,fp))
- {
- if(strstr(linebuf,Section))
- {
- fgets(linebuf,1024,fp);
- if(strstr(linebuf,Item))
- {
- if(value=strchr(linebuf,'='))
- {
- value++;
- printf("value = %s /n",value);
- return value;
- }
- }
- }
- }
- return (char*)NULL;
- }
- int main(void)
- {
- FILE *fp;
- char *value;
- if((fp=fopen("test.ini","rb"))==(FILE*)0)
- {
- printf("open file error!/n");
- exit(1);
- }
- value=GetIniSectionItem(fp,"TEST","NAME");
- fclose(fp);
- printf("value1 = %s/n",value);
- return 0;
- }
大家可以实验下:
test.ini
[dddd]
dsfsd=sdfs
[TEST3]
NAMe=robertluo3
[TEST!]
nAME=robertluo1
[TESt]
NAME=robertluo2
[TEST]
NAME=robertluo
输入结果为:
value = robertluo
当项目在文件中有多个时,返回第一个项目的值。
评论暂时关闭