-1

I am trying to write a C program that is able to read data (strings) from a text file and swap each content in terms of bytes. I have already implemented the code and everything works just fine, and and I am able to read all the contents of the specified text file, but the problem is that the program is printing the last word from the text file twice and I do not know why? Any help will be helpful ! This is the code I have:

while( !feof(ptr_file))
{
    //to read in group of words (sentences) if
    //needed !.
    fscanf(ptr_file, "%s", userName);   
    //time to swap letters of the word coming from the text file.
    swap_a_word(userName, 0, 4);
    swap_a_word(userName, 1, 2);
    //new space.
    printf("\n");
    //display the word after swapping to the screen for the user.   
    printf("%s", userName);
}

The program must not print extra data. I do not know, but when the program reaches the end of the file, it prints the last data of the text file twice. Please any hints will be helpful !.

Thanks !

harald
  • 5,976
  • 1
  • 24
  • 41
  • Your use of `feof()` is wrong. Read http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong – pmg May 08 '14 at 08:04

1 Answers1

0

The problem is the while loop condition

while(!feof(ptr_file))

Note that EOF is preceded by a newline '\n'. fscanf returns the value EOF when the end of file is reached. However, this does not set the end-of-file indicator on the stream and as a result the loop is entered one extra time. You should check the return value of fscanf instead to find number of items successfully matched and assigned.

ajay
  • 9,402
  • 8
  • 44
  • 71