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!

13 Years
Discussion Span
Last Post by Narue

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.


>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:

while ( !feof ( in ) ) {
  /* Read from the file and process */

Or this:

while ( !in.eof() ) {
  // Read from the file and process

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:

while ( fgets ( line, sizeof line, in ) != NULL ) {
  /* Process and print */


while ( getline ( in, line ) ) {
  // Process and print

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.