配置文件解析c中的字符串匹配错误

问题描述 投票:0回答:1

虽然我知道有用于配置文件解析的库我已经尝试编写自己的实现。问题是我可以找到配置选项,但是当我尝试将它与我正在搜索的东西进行比较时,在分隔符失效之前比较字符串。我需要将它与我正在搜索的内容相媲美,因为我的程序允许像Test2和Test3这样的东西,因为它无法检查单词Test之前或之后是否有字符。比较总是失败,我无法弄清楚为什么。这是我的代码:

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
c parsing config file-read
1个回答
0
投票

感谢BLUEPIXY和他们创建的演示这个问题已经解决了。问题出在我忘记的gcc编译器选项-std = 99,这导致程序行为正常。

© www.soinside.com 2019 - 2024. All rights reserved.