0

I'm taking my first programming class ever this year and I'm slight confused on this. I'm trying to learn the fopen and fclose functions currently.

My code is

int main(void)
{
        FILE *input; /* Pointer to the input file */
        double values;
        double sum;

input = fopen("data.dat", "r"); /* Prepare file for input */

sum = 0;
while (!feof(input))
{       fscanf(input, "%lf", &values);
    sum = sum + values;
}

printf("The sum of the values is %f\n", sum);

fclose(input);
return 0;
}

When I compile this to get the sum, the last value of the data.dat file is counted for twice. I was wondering how I could fix this. Thanks!

Pudge
  • 1

1 Answers1

1

You should not use while(!feof(...)) because it's always wrong. Why?

It will, as you found out, loop one more time than you expect. That happens because the semantics of feof() are not what you think: that is, they are not to check if the next read will reach the end of file. Instead, feof allows you distinguish between a read error and the end of the file after you get a zero from a read (or some other similar call).

The solution to your problem is easy: use the functions you call properly. fscanf returns a value - you should find out what that value is and, more importantly, what it means.

Nik Bougalis
  • 10,495
  • 1
  • 21
  • 37