简易键值对文本解析
除了json,xml,protobuf等成体系的配置文件外,简单的文本格式“key value”的配置文件也在很多开源项目中存在,这种配置文件的好处是简单、易于理解和编辑。
#include <stdio.h>
#include <string.h>
#define MAX_LINE_LENGTH 1024
void ParseConfig(const char *filePath)
{
FILE *file = fopen(filePath, "r");
if (file == NULL)
{
perror("Error opening file");
return;
}
char line[MAX_LINE_LENGTH];
while (fgets(line, sizeof(line), file) != NULL)
{
// 去掉行末尾的换行符
line[strcspn(line, "\r\n")] = '\0';
// 忽略注释和空行
if (line[0] == '#' || line[0] == '\0')
{
continue;
}
// 解析配置项
char *key = strtok(line, " \t");
char *value = strtok(NULL, " \t");
if (key != NULL && value != NULL)
{
printf("%s %s\n", key, value);
}
}
fclose(file);
}
int main()
{
const char *filePath = "config.txt";
ParseConfig(filePath);
return 0;
}