Linux C 读取ini格式(key&value)配置文件

2019-07-13 00:38发布


在Windows下可以用GetPrivateProfileString或GetPrivateProfileInt方便读取.ini配置文件内容,
但是在Linux平台上就一筹莫展了。

为了解决该问题,打算用C来读取.ini,就可以不受平台的限制了。

配置文件Config.ini
[test]
name=elikang
age=12


读取配置文件的程序:
#include
#include
#include
#include
#include
#include

//read string from config file
char *get_string_from_ini(char *title, char *key, char *filename)
{
FILE *fp;
char szLine[1024];
static char tmpstr[1024];
int rtnval;
int i = 0;
int flag = 0;
char *tmp;

if((fp = fopen(filename, "r")) == NULL)
{
perror("fopen()");
return NULL;
}

while(!feof(fp))
{
rtnval = fgetc(fp);
if(rtnval == EOF)
{
break;
}
else
{
szLine[i++] = rtnval;
}

if(rtnval == ' ')
{
szLine[--i] = ' ';
i = 0;
tmp = strchr(szLine, '=');

if((tmp != NULL) && (flag == 1))
{
if(strstr(szLine, key) != NULL)
{
//comment
if('#' == szLine[0]);
else if('/' == szLine[0] && '/' == szLine[1]);
else
{
//local key position
strcpy(tmpstr, tmp+1);
fclose(fp);
return tmpstr;
}
}
}
else
{
strcpy(tmpstr, "[");
strcat(tmpstr, title);
strcat(tmpstr, "]");

if(strncmp(tmpstr, szLine, strlen(tmpstr)) == 0)
{
//encounter title
flag = 1;
}
}
}
}

fclose(fp);
return "";
}

int get_int_from_ini(char *title, char *key, char *filename)
{
return atoi(get_string_from_ini(title, key, filename));
}

int main(int argc, char **argv)
{
char name[1024];
int age = 0;

memset(name, 0, sizeof(name));

age = get_int_from_ini("test", "age", argv[1]);
strcpy(name, get_string_from_ini("test", "name", argv[1]));

//puts(name);
printf("%s", name);
printf("age = %d ", age);
}