End of file controlled loop

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Oct 2006
Posts: 6
Reputation: SammyHasibi is an unknown quantity at this point 
Solved Threads: 0
SammyHasibi SammyHasibi is offline Offline
Newbie Poster

End of file controlled loop

 
0
  #1
Oct 9th, 2006
  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
Reply With Quote Quick reply to this message  
Join Date: Jun 2005
Posts: 275
Reputation: andor has a spectacular aura about andor has a spectacular aura about andor has a spectacular aura about 
Solved Threads: 29
andor's Avatar
andor andor is offline Offline
Posting Whiz in Training

Re: End of file controlled loop

 
1
  #2
Oct 9th, 2006
Read this
If you want to win, you must not loose (Alan Ford)
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC