hitman.star
hitman.star

Reputation: 73

reading ini files using fscanf in c

I'm having a problem parsing an .ini file. I know there are lots of post on this topic, and I have read many of them. my ini file have only one entry:

font=tahoma.ttf

Source Code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

static FILE *ini_file;
char font[20];

void LoadConfig()
{
    char Setting[20],Value[20];
    int EndOfFile = 0;
    if ((ini_file = fopen("config.ini", "r")))
    {
        EndOfFile = fscanf(ini_file, "%[^=]=%s", Setting, &Value);
        while (EndOfFile != EOF)
        {
            if(strcmp(Setting,"font") == 0)
            {
                strcpy(font,Value);
            }
            EndOfFile = fscanf(ini_file, "%[^=]=%s", Setting, &Value);
        }
        fclose(ini_file);
    }
}

The problem is that, the value is not never read into the font variable.

Upvotes: 1

Views: 1959

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 149095

SefFault could be caused by the & before Value, but even after removing if, you could still read a value longer than 20 characters. And some ini files can contain comment lines that does not follow the pattern and will break you progran

You really should:

  • read line by line with fgets into a buffer of at least 255 characters - repeat until end of file : while (NULL != fgets(line, sizeof(line), stdin)) { ...}
  • use sscanf to parse each line and ignore every non conformant one:

    if (2 == sscanf(line, "%19[^=]=%19s", Setting, Value) { ... }
    

Upvotes: 3

user3121023
user3121023

Reputation: 8286

Use fgets to read each line in the file. strpbrk could be used to locate the equal and the newline and copy that span of characters to the variables.

void LoadConfig()
{
    char Setting[100] = {'\0'},Value[100] = {'\0'}, line[300] = {'\0'};
    size_t span = 0;
    if ((ini_file = fopen("config.ini", "r")))
    {
        while ( fgets ( line, sizeof ( line), ini_file))//read each line
        {
            char *equal = strpbrk ( line, "=");//find the equal
            if ( equal)//found the equal
            {
                span = equal - line;
                memcpy ( Setting, line, span);
                Setting[span] = '\0';
                if(strcmp(Setting,"font") == 0)
                {
                    equal++;//advance past the =
                    char *nl = strpbrk ( equal, "\n");//fine the newline
                    if ( nl)//found the newline
                    {
                        span = nl - equal;
                        memcpy ( font, nl, span);
                        font[span] = '\0';
                    }
                }
            }
        }
        fclose(ini_file);
    }
}

Upvotes: 1

Related Questions