{
FILE *scorefile;
int score;
int temp;
scorefile = fopen("scores.txt","r");
if (scorefile == NULL)
printf("Error opening input file\n");
else
{
temp = 0;
while (feof(scorefile) <= 0)
{
fscanf(scorefile,"%d",&score);
temp = temp +1;
}
}
fclose(scorefile);
printf("Temp = %d\n",temp);
system("pause");
return(0);
}
The program counts the number of terms in the file "scores.txt".
An end-of-file-controlled loop is used to read values until the end of file is encountered.
This sort of loop uses the fact that a file goes into the fail state when you try to read a
data value beyond the end of a file to control it.
The value of "temp" will be 6 at the end of the program but it was 0 at the beginning. The
value of temp is determined by its placement in the end-of-file controlled loop whereby
it loops once for every individual term it encounters and adds the value of 1 for
each. After each iteration it checks with the condition enclosed within the parentheses
that "feof(scorefile) . . ."
Is there a better, more economical way of saying this (the file has 6 values within it)?
Thanks for viewing :)