【问题标题】:Error using while loop and eof on C在 C 上使用 while 循环和 eof 时出错
【发布时间】:2025-12-15 19:05:02
【问题描述】:

我是 C 初学者,我尝试编写代码以从文件中读取浮点数,从单独的行中读取,这是我的尝试

#include <stdio.h>
#include<math.h>

int main (void)
{
FILE *fb;
FILE *fp;
fb=fopen("sumsquaresin.txt","r");
fp=fopen("q1out.txt","w");
float x,y,z = 0.0;
int n = 1.0,result;
result =fscanf(fb,"%f",&x);

while(result!=EOF)
{
    y=pow(x,2.0);
    z+=y;

if(result == EOF)
    break;
    n++;

}
fprintf(fp,"%d were read\n",n);
fprintf(fp,"The sum of squares is %.2f\n",y);
fclose(fb);
fclose(fp);
return 0;
}

我不断收到 NULL 和在线绿色错误:

result =fscanf(fb,"%f",&x);

错误信息显示“线程 EXC_BAD_ACCESS(code=1,address=0x68”

任何帮助将不胜感激,谢谢

【问题讨论】:

  • 循环中result 没有任何变化;如果进入循环,则不会退出循环。假设您成功打开它,您也只会从文件中读取第一个数字。您可能应该使用while (fscanf(fb, "%f", &amp;x) == 1) { ... } 来控制循环。

标签: c file while-loop eof


【解决方案1】:

@Gangadhar 正确测试您的 fb 是否为 NULL。

另外:

if (fp == NULL) {
  retunr -1 ; ;; handle open error
}

将您的 fscanf() 移动到循环中并进行测试,不是针对 EOF,而是针对 1。

// int n = 1.0;
int n = 1;
while ((result = fscanf(fb,"%f",&x)) == 1) {
  y = x*x;  // pow(x,2.0);
  z += y;
  n++;
}
if (result != EOF) {
  ; // handle_parsing error
}

建议在代码中使用更多的空间和更好的变量名。

【讨论】:

    【解决方案2】:

    检查fopen的返回值,如果失败则为NULL,则不能使用FILE指针。

    fb = fopen("sumsquaresin.txt", "r");
    if(fb == NULL){
        // print error and bail
        return 1;
    }
    

    【讨论】:

    • @Gangadhar 我用return 1;表示无法fopen的失败
    • 误解了。该更改恢复了。