944,140 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 6735
  • C RSS
Oct 9th, 2006
0

End of file controlled loop

Expand Post »
  1. {
  2. FILE *scorefile;
  3. int score;
  4. int temp;
  5.  
  6. scorefile = fopen("scores.txt","r");
  7. if (scorefile == NULL)
  8. printf("Error opening input file\n");
  9. else
  10. {
  11. temp = 0;
  12. while (feof(scorefile) <= 0)
  13. {
  14. fscanf(scorefile,"%d",&score);
  15. temp = temp +1;
  16. }
  17. }
  18. fclose(scorefile);
  19. printf("Temp = %d\n",temp);
  20. system("pause");
  21. return(0);
  22. }
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
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
SammyHasibi is offline Offline
6 posts
since Oct 2006
Oct 9th, 2006
1

Re: End of file controlled loop

Read this
Reputation Points: 251
Solved Threads: 29
Posting Whiz in Training
andor is offline Offline
274 posts
since Jun 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: Problem starting a homework problem for class. Please help!
Next Thread in C Forum Timeline: help with conversion calculator





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC