【问题标题】:Program crashes after fscanf() encounters EOFfscanf() 遇到 EOF 后程序崩溃
【发布时间】:2016-10-16 10:33:18
【问题描述】:

我什至不确定 fscanf() 是否真的遇到 EOF。这是我的代码

#include<stdio.h>

int main()
{
int i=0,a[13];
FILE *fp;
fp=fopen("test.txt","r");
if(fp==NULL)
{
    printf("Error");
}
else
{
    i=0;
    while((fscanf(fp,"%d",&a[i]))!=EOF)
    {
        printf("%d\n",a[i]);
        i++;
    }
    printf("%d",i);
}
fclose(fp);
return 0;
}

测试输入是:

12
32
45
65
92
-1
0
61
15
13
12
240
4

我在代码块中运行它。

This is the runtime condition

【问题讨论】:

  • 请详细说明您的问题
  • 可能不相关,但是如果fopen 返回NULL,您的程序可能会崩溃,因为在这种情况下您不应该调用fclose。如果你的文件中有超过 13 个整数,它也很可能会崩溃。
  • while((fscanf(fp,"%d",&amp;a[i]))!=EOF &amp;&amp; i &lt; 13){…}

标签: c file-io file-handling eof scanf


【解决方案1】:

这与fsanf() 返回EOF 无关,而是在此之前,通过提供更长 输入序列,您将超出目标数组a。尝试访问超出范围的内存调用undefined behavior。结果可以是任何东西

当您已经有一个固定长度的数组时,不要允许存储任意数量的输入,通过数组大小来限制索引 (arraysize-1)。

【讨论】:

【解决方案2】:

您的输入有 14 个元素,您尝试将它们读入 13 个元素数组 a[13]。这就是为什么你有一个崩溃。 增加数组的大小或防止数组溢出。例如

#include<stdio.h>

#define ARR_SIZE 14

int main()
{
  int i;
  int a[ARR_SIZE];
  FILE *fp;

  fp=fopen("test.txt","r");
  if(fp==NULL)
  {
     printf("File open error\n");
  }
 else
 {
      i=0;
      while ( (i<ARR_SIZE) && (fscanf(fp,"%d",&a[i]))!=EOF)
      {
         printf("%d\n",a[i]);
         i++;
      }

   printf("%d",i);
  }

  fclose(fp);
  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 2016-04-13
    • 2016-12-28
    • 2021-03-02
    • 2012-04-16
    相关资源
    最近更新 更多