user2876531
user2876531

Reputation: 11

Error using while loop and eof on C

I'm a C beginner I trying to write a code to read floats from a file, from separate lines and heres my try

#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;
}

I keep getting NULL and a green error on line:

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

The error message says"thread EXC_BAD_ACCESS(code=1,address=0x68"

any help would be appreciated, thank you

Upvotes: 1

Views: 288

Answers (2)

Kninnug
Kninnug

Reputation: 8053

Check the return value of fopen, if it fails it will be NULL and then you can't use the FILE pointer.

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

Upvotes: 2

chux
chux

Reputation: 154136

@Gangadhar is correct to test your fb against NULL.

Additionally:

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

Move your fscanf() into the loop and test, not against EOF, but 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
}

Recommend more use of space in code and better variable names.

Upvotes: 2

Related Questions