【发布时间】:2019-03-29 00:47:42
【问题描述】:
在 c 编程中从配置文件中读取名称及其值的最佳方法是什么?
示例配置文件:
NAME=xxxx
AGE=44
DOB=mmddyyyy
WORK=zzzz
这是我正在使用的代码。这是工作。但我想知道是否有更好的方法。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getValue(char *line, char* name, char value[])
{
char* pch = NULL;
char* token = NULL;
pch = strstr(line, name);
if(pch)
{
token = strtok(pch, "=");
while (token != NULL)
{
pch = token;
token = strtok(NULL, "=");
}
pch[strcspn ( pch, "\n" )] = '\0';
strcpy(value,pch);
return 1;
}
return 0;
}
int main()
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
char value[100];
int ret = 0;
fp = fopen("test.txt", "r");
if (fp == NULL)
{
printf ("Cannot open file \n");
return -1;
}
while ((read = getline(&line, &len, fp)) != -1)
{
ret = getValue(line,"NAME",value);
if (ret)
{
printf("NAME is %s\n", value);
}
ret = getValue(line,"AGE",value);
if (ret)
{
printf("AGE is %s\n", value);
}
}
free(line);
fclose(fp);
return 0;
}
如果此代码有任何问题,我也很乐意听到。
【问题讨论】:
-
最好的方法是使用明确构建的库来处理此类事情。