2017-09-13 132 views
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 
+0

請更正確地解釋你的問題。讓我們知道,你究竟想要什麼 –

+2

小程序,很少輸入數據,...開始學習如何調試程序的完美場所。 – Gerhardh

+1

_比較總是失敗_:與'Test'比較成功,獲得'1234'。 [DEMO](https://wandbox.org/permlink/dxtr7QzBkcljNlbc) – BLUEPIXY

回答

0

感謝BLUEPIXY和他們創造的演示這個問題已經解決了。這個問題出現在我忘記的gcc comiler選項中--std = 99不知何故,這導致程序行爲正常。