2015-03-02 71 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文件上运行会导致程序崩溃。