End of file function

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

Join Date: Oct 2004
Posts: 1
Reputation: Erica is an unknown quantity at this point 
Solved Threads: 0
Erica Erica is offline Offline
Newbie Poster

End of file function

 
0
  #1
Oct 3rd, 2004
My program is reading the last line of data from an infile twice. When I execute the program, the last line of data is being displayed twice. Please Help!
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 11
Reputation: ilvmdy is an unknown quantity at this point 
Solved Threads: 0
ilvmdy ilvmdy is offline Offline
Newbie Poster

Re: End of file function

 
0
  #2
Oct 4th, 2004
Hey Erica,
Welcome to the forum. I not a big expert or anything but I do know that most of the people like to see the program code so they can tell you exactly what is wrong. Hopefully someone can help.
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 7,783
Reputation: Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute 
Solved Threads: 745
Team Colleague
Narue's Avatar
Narue Narue is offline Offline
Code Goddess

Re: End of file function

 
0
  #3
Oct 4th, 2004
>My program is reading the last line of data from an infile twice.
I'll bet my next paycheck that your file processing loop looks like this:
  1. while ( !feof ( in ) ) {
  2. /* Read from the file and process */
  3. }
Or this:
  1. while ( !in.eof() ) {
  2. // Read from the file and process
  3. }
The problem with that is feof (or stream.eof ) only returns true after an attempt has been made to read from the file and end-of-file was encountered. So your loop will iterate once more than you want, and because the input request failed you will use the last successfully read line. The result is that the last line of the file is processed twice.

The solution is to use the return value of your input function as the loop condition:
  1. while ( fgets ( line, sizeof line, in ) != NULL ) {
  2. /* Process and print */
  3. }
Or
  1. while ( getline ( in, line ) ) {
  2. // Process and print
  3. }
As an alternative, you can use an infinite loop and use feof or stream.eof in an if statement immediately after your input functions read from the file. That way you can break from the loop before processing the last line twice.
I'm here to prove you wrong.
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