Search code examples
cparsingconfigfile-read

Config file parsing string matching error in c


While I am aware there are libraries for config file parsing I have tried to write my own implementation. The problem is that I can find the config option but comparing the string before the delimeter failes when I try to compare it with the thing I am searching for. I need to comare it with the thing I am searching for becasue my program allows things like Test2 and Test3 because it cannot check if there are characters before or after the word Test. The compare allways failes and I cannot figure out why. Here is my code:

Main.c

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

void Parser(char *CONFIG_FILE, int *P_VALUE, char *STRING_TO_LOOK_FOR);

int main(){
    int VALUE;
    Parser("config.txt", &VALUE, "Test");
    printf("%d \n", VALUE);
}

Parser.c:

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

void Parser(char *CONFIG_FILE, int *P_VALUE, char *STRING_TO_LOOK_FOR){
    FILE *FP=fopen(CONFIG_FILE,"a+");
    char TMP[256]={0x0};
    int i = 1;
    while(FP!=NULL && fgets(TMP, sizeof(TMP), FP)!=NULL){ //Loop through every line
        i=i+1; //Increment the line number
        if (strstr(TMP, STRING_TO_LOOK_FOR)){ //Is the term im looking for in this line
            char *NAME_OF_CONFIG_STR = strtok(TMP, "= "); //look for delimiter
            char *STRVALUE = strtok(NULL, "= "); //Get everything past the delimiter
            char *P_PTR;
            char *pos;
            if ((pos=strchr(NAME_OF_CONFIG_STR, '\n')) != NULL){ //attempt remove \n doesn't work
                *pos = '\0';
            }

            if(strcmp(STRING_TO_LOOK_FOR, NAME_OF_CONFIG_STR) == 0){ //try to check the two are the same
                *P_VALUE = strtol(STRVALUE, &P_PTR, 10); //Returns an integer to main of the value
            }
        }
    }
    if(FP != NULL){
        fclose(FP);
    }
}

config.txt:

Test= 1234
Test2= 5678
Test3= 9012

Solution

  • Thanks to BLUEPIXY and the demo they created this problem has been solved. The issue was in the gcc comiler options I had forgotten -std=99 somehow this caused the program to behave correctly.