【发布时间】:2020-07-16 05:41:17
【问题描述】:
我正在尝试仅使用 C 中的标准库来解析 .ini 文件。 输入文件如下所示:
[section1]
key1 = value1
key2 = value2
[section2]
key3 = vaule3
key4 = value4
key5 = value5
...
我用./file inputfile.ini section2.key3 运行它,我想从 section2 获取 key3 的值
我的问题是:如何轻松存储键和值? - 我是一个初学者,所以我需要一些简单且易于实现的东西 - 也许是 struct 但如果我不知道键的数量,如何将所有键和值存储在 struct 中?
我卡在这里,两个字符串部分和 current_section 看起来相同,但在 if(section == current_section) 他们没有通过 True,有什么问题?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE * fPointer;
fPointer = fopen(argv[1], "r"); // read from file
char singleLine[30];
char section[30];
char key[30];
int right_section = 0;
char current_section[30];
sscanf(argv[2], "%[a-zA-Z0-9].%[a-zA-Z0-9]", section, key); //split of section.key
while(!feof(fPointer)){
fgets(singleLine, 30, fPointer); //read line by line
printf("%s", singleLine);
char current_key[30];
char current_value[30];
if(singleLine[0]=='['){
sscanf(singleLine, "[%127[^]]", current_section); //strip from []
printf("current section:%s%s", current_section, section); //both look equally
if(current_section == section){ // doesn't work here, current_section == section looks the same but if doesnt work
right_section = 1;
printf("yes, right");
}
}
}
fclose(fPointer);
return 0;
}```
【问题讨论】:
-
这能回答你的问题吗? INI file parser for C
-
好吧,只需将带有
fgets()的每一行读入一个足够大的字符数组(不要吝啬大小),比如buf,然后检查buf[0] == '['(或只是*buf == '['),如果是这样,则使用sscanf()将部分名称读入另一个数组,如果不是您的部分,请继续阅读直到下一个'[',直到找到您的部分,然后使用fgets()读取,使用sscanf()分隔成@987654334 @ 和value字符串,直到您匹配您的搜索条件。 -
@DavidC.Rankin 谢谢伙计,我没有这样想。你能告诉我如何存储每个部分及其键和值吗?我应该使用什么,那会是什么样子?我知道我不需要为我的问题存储它们,但我想知道
-
好吧,首先将您的输入作为
./file inputfile.ini section2 key3并省去拆分section2.key3会更有意义。然后我会声明char buf[256], sect[128], key[128], value[128];打开您的文件并验证它是否已打开以供阅读。然后while (fgets (buf, sizeof buf, fp)) { ...读取每一行测试if (buf[0] == '[') { ...找到每个部分的开始。然后您可以阅读带有if (sscanf (buf, " [%127[^]]", sect) == 1)的部分并测试if (strcmp (sect, argv[2]) == 0)以查看您是否匹配您的部分。然后使用sscanf拆分键/值。 -
如果您遇到困难,请编辑您的问题并将您目前所拥有的内容添加到问题的末尾,我很乐意为您提供进一步的帮助。对于一个简单的方法,您可以循环查找您的部分,
break当您用正确的部分填充sect变量时循环。现在你可以检查if (feof(fp)) { printf ("error: end of section '%s' reached with no matching key found.\n", sect); return 1; )然后你可以进入你的第二个循环来匹配key和val。要解析key和val的sscanf()格式字符串将类似于" %127s = %127s"。