Home > Enterprise >  C - parse key-value pairs from ASCII file
C - parse key-value pairs from ASCII file

Time:11-07

I am trying to write a C function that reads the key-value pairs stored in an ASCII file that looks as follows (the text that indicates to ignore a certain line or part of a line is not in the file, of course: I added it for clarity):

[SECTION 1 HEADER - ignore this line]
VAR1             =   'xyz'
VAR2          =   3.0
VARIAB3           =   'blabla'
! COMMENT: ignore this line              VAR7 =      'ABC123'
$---------another line to ignore----------------- 
[SECTION 2 HEADER - ignore me!]
varname8                =        'abcd'
$---------yet another line to ignore-----------
[SECTION HEADER - ignore me]
VARIABLE10 =    4.05101e 05      $ignore from the dollar sign to eol
VARIABLE13 =    7e-06      $ignore from the dollar sign to eol
param_1=123
param_2=321

As you can see, not all the lines contain (key,value) pairs I would like to retain. Also, the names of the keys don't always have the same length and the values can be strings or numbers... Moreover, the '=' sign can be preceded and/or followed by zero or more spaces. Finally, comments appearing after the key,value pair should be ignored.

I've tried the following code to read from the file and parse the key-value pairs:

fh = fopen(filename, "r");
    if(NULL == fh) {
        perror(filename);
    }
    else
    {
        printf("File opened succesfully.\n");
        while(fgets(buffer, 100, fh) != NULL)
        {
            {
                int offset;
                int res = sscanf(buffer, "%s = %s%n", key, value, &offset);
                if(res==2)
                {
                    printf("Found: %s = %s\n", key, value);
                }
            }   
        }
    }

which gives the following output, clearly failing at capturing the last two key-value pairs:

Filename is: sample.tir
File opened succesfully.
Found: VAR1 = 'xyz'
Found: VAR2 = 3.0
Found: VARIAB3 = 'blabla'
Found: varname8 = 'abcd'
Found: VARIABLE10 = 4.05101e 05
Found: VARIABLE13 = 7e-06
File closed.

I believe the problem might be in the format string for sscanf: any ideas?

CodePudding user response:

I suggest you check for and overwrite the '=' character, to separate the key and value. Perhaps like this snippet

char *ptr = strchr(buffer, '=');        // find the '='
if(ptr == NULL)
    continue;
*ptr = ' ';                             // replace with a space
int res = sscanf(buffer, "%s%s", key, value);
if(res != 2)
    continue;
printf("Found: %s = %s\n", key, value);

Output

Found: VAR1 = 'xyz'
Found: VAR2 = 3.0
Found: VARIAB3 = 'blabla'
Found: varname8 = 'abcd'
Found: VARIABLE10 = 4.05101e 05
Found: VARIABLE13 = 7e-06
Found: param_1 = 123
Found: param_2 = 321
  • Related