Anamika Ana
Anamika Ana

Reputation: 175

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

I have created a .ini file that looks as follows:

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

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

The main C program to access this ini file looks like this:

#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;

}

I am able to display the whole heading from setion one and also the whole array name. But instead of displaying the whole array (name) like this

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

I just want to display the term 'A'. Similarly for the section two instead of this

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

I just want to diaply the "on". I cannot figure out a way to do this. Can somebody help me out please?

Upvotes: 2

Views: 3498

Answers (2)

Adriano Repetti
Adriano Repetti

Reputation: 67128

INI files are pretty simple, there isn't anything like an array then you have to split that string by yourself.

Fortunately it's pretty easy (let me assume we can omit [ and ] because they don't add anything for this example):

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");
}

For string trimming (bot for [, spaces and eventually quotes) you may use code from How do I trim leading/trailing whitespace in a standard way?.

(please note that code is untested)

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409364

One way to solve your problem is to parse it yourself (that's really the only way to do it), and one way of parsing it is something like this:

  1. Remove the leading and trailing '[' and ']' (read about the strchr and strrchr functions respectively)
  2. Split the remaining string on the comma ',' (read about the strtok function)
  3. For each sub-string, remove leading and trailing white-space (read about the isspace function)
  4. You now have the values, and can put them into a list or an array of strings

Upvotes: 1

Related Questions