2015-03-02 69 views
-2

我在代碼中發現分段錯誤時遇到問題,我對編碼不熟悉,沒有訓練有素的眼睛。非常感謝幫助!分段錯誤:C中有11個

#include <stdio.h> 
#include <ctype.h> 

int main(void){ 

    FILE *input_file; 

    int num0 = 0, num1 = 0, num2 = 0, num3 = 0, num4 = 0; 
    int num5 = 0, num6 = 0, num7 = 0, num8 = 0, num9 = 0; 
    char c; 


    input_file=fopen("data.txt", "r"); 

    while (!feof(input_file)) { 

     c = fgetc(input_file); 

     if (isdigit(c)) { 

      if (c=='0') num0++; 
       else if (c=='1') num1++; 
       else if (c=='2') num2++; 
       else if (c=='3') num3++; 
       else if (c=='4') num4++; 
       else if (c=='5') num5++; 
       else if (c=='6') num6++; 
       else if (c=='7') num7++; 
       else if (c=='8') num8++; 
       else if (c=='9') num9++; 
     } 

     else if (c=='E'){ 
      c = fgetc(input_file); 
      if (c=='N'){ 
       c = fgetc(input_file); 
       if (c=='D') { 
        break; 
       } 
      } 
     } 
    } 


    printf("Number of 0: %d\n", num0); 
    printf("Number of 1: %d\n", num1); 
    printf("Number of 2: %d\n", num2); 
    printf("Number of 3: %d\n", num3); 
    printf("Number of 4: %d\n", num4); 
    printf("Number of 5: %d\n", num5); 
    printf("Number of 6: %d\n", num6); 
    printf("Number of 7: %d\n", num7); 
    printf("Number of 8: %d\n", num8); 
    printf("Number of 9: %d\n", num9); 

他們希望我沒有那麼多的代碼,而無需編寫
FCLOSE(INPUT_FILE);

} 
+0

fclose在上面的評論應該是在代碼 – 2015-03-02 22:19:02

+2

有問題下的編輯鏈接。 – Celeo 2015-03-02 22:22:26

+1

你在哪裏得到段錯誤?您應該可以使用'gdb'將錯誤追溯到破壞代碼的確切行。 – 2015-03-02 22:34:44

回答

0

有幾個讀(fgetc)與單EOF檢查循環。如果前一次讀取到達EOF,則某些讀取可能會嘗試讀取結束的文件。

+0

這不應該AFAIK;一旦你在文件的最後(只要你不關閉它),'fgetc'就會繼續返回EOF。 – nneonneo 2015-04-10 16:06:06

+0

這不應該以段錯誤結束 – zoska 2015-04-10 16:16:01

1

確保輸入文件存在。如果沒有,或者無法訪問,則fopen返回NULL。嘗試在NULL文件上運行會導致程序崩潰。