如何从 C 中的 ini 文件访问数组?

How To access an Array from a ini file in C?

我创建了一个 .ini 文件,如下所示:

[one]
heading=" available state";
name=['A', 'D', 'H'];

[two]
type= ["on", "off", "switch"];

访问此 ini 文件的主要 C 程序如下所示:

#include <stdio.h>
#include <Windows.h>

int main ()
{

   LPCSTR ini = "C:\coinfiguration.ini";

   char returnValue1[100];
   char returnValue2[100];
   GetPrivateProfileString("states", "title", 0, returnValue1, 100, ini);
   GetPrivateProfileString("reaction", "reac_type", 0, returnValue2, 100, ini);

   printf(returnValue2[10]);

   printf("%s \n" ,returnValue1);
   printf(returnValue2);



   return 0;

}

我能够显示第一个部分的整个标题以及整个数组名称。但不是像这样显示整个数组(名称)

['A', 'D', 'H']; 

我只想显示字词'A'。 同样对于第二部分而不是这个

["on", "off", "switch"];

我只想透析"on"。 我想不出办法做到这一点。有人可以帮我吗?

解决问题的一种方法是自己解析(这确实是唯一的方法),还有一种方法解析它是这样的:

  1. 删除前导和尾随 '['']'(分别阅读 strchr and strrchr 函数)
  2. 用逗号 ',' 拆分剩余的字符串(阅读 strtok 函数)
  3. 对于每个子字符串,删除前导和尾随的白色-space(阅读 isspace 函数)
  4. 您现在有了值,可以将它们放入列表或字符串数​​组中

INI文件很简单,没有数组之类的东西,你必须自己拆分那个字符串。

幸运的是这很容易(让我假设我们可以省略 [] 因为他们没有为这个例子添加任何东西) :

char* buffer = strtok(returnValue1, ",");

for (int i=0; i <= itemIndex && NULL != buffer; ++i) {
    buffer = strtok(NULL, ",");
    while (NULL != buffer && ' ' == *buffer)
        ++buffer;
}

if (NULL != buffer) { // Not found?
    printf("%s\n", buffer);

    if (strcmp(buffer, "'A'") == 0)
        printf("It's what I was looking for\n");
}

对于字符串修剪([、空格和引号的机器人),您可以使用 How do I trim leading/trailing whitespace in a standard way?.

中的代码

(请注意代码未经测试)