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


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

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

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


读取配置文件的程序:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <stdarg.h>

//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 == '\n')
{
szLine[--i] = '\n';
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\n", age);
}




 

猜你喜欢

转载自blog.csdn.net/elikang/article/details/85326597