在C上使用while循环和eof时出错

时间:2013-10-13 17:04:04

标签: c file while-loop eof

我是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);

错误消息显示“thread EXC_BAD_ACCESS(code = 1,address = 0x68”

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

2 个答案:

答案 0 :(得分:2)

检查fopen的返回值,如果失败,则为NULL,然后您无法使用FILE指针。

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

答案 1 :(得分:2)

@Gangadhar测试你的fb是否正确。

此外:

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
}

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