0
虽然我知道有配置文件解析的库我试图写我自己的实现。问题是,我可以找到配置选项,但比较字符串之前,当我尝试与我正在寻找的东西进行比较时,分隔符失败。我需要将它与我正在寻找的东西相关联,因为我的程序允许像Test2和Test3这样的东西,因为它无法检查单词Test之前或之后是否有字符。比较总是失败,我不明白为什么。 这里是我的代码:配置文件解析字符串匹配错误在c
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
请更正确地解释你的问题。让我们知道,你究竟想要什么 –
小程序,很少输入数据,...开始学习如何调试程序的完美场所。 – Gerhardh
_比较总是失败_:与'Test'比较成功,获得'1234'。 [DEMO](https://wandbox.org/permlink/dxtr7QzBkcljNlbc) – BLUEPIXY