0

I am working now on pset5, trying to degrade each task into pieces. So now, I have written some code that just reads words from a file I have created, it then prints each word it read. The problem is that the program prints the last word twice. I don't know why.

Here is the code

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define LENGTH 45
int main() {

 char * word = malloc(sizeof(char)*LENGTH);
        FILE * fp = fopen("source.txt","r");
        if (fp ==NULL) {
                printf("File not found!\n");
                return 1;
        }       
        do {
        fscanf(fp,"%s",word);
        *word = tolower(*word);
        printf("%s \n",word);
        }
        while(!feof(fp));
        free(word);
        fclose(fp);
}

1 Answer 1

0

It's all about the sequence. The code reads a word, prints it, and then checks for EOF. You need to understand that the EOF is only detected when it is actually processed, not when it's about to be processed.

In your example, the last word is read and the file pointer is left pointing at the next thing to be read, the EOF, but the EOF has not yet been read/detected, meaning that the pointer is not yet set to indicate EOF. (Think of it as walking up to the end of a diving board, but not yet stepping off. You're still dry, but water is in the next step.) So, the last word is printed and the feof() call that follows does not yet detect the end of file, and the loop runs again. On the next read, the EOF is actually registered in the file pointer, but since nothing was read in, the previous contents remain in word, which is then printed. Now, when the feof() call executes, it sees the end of file has now been detected and the loop terminates.

The EOF condition needs to be checked when the read occurs or immediately after. Two methods are to either test for the EOF immediately after the read, or to incorporate the read into the while condition and test for EOF as part of the read.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • Can you please provide the code for the change to be done? Commented May 18, 2016 at 11:30
  • While it would be easy for me to provide code, this is a class/learning environment. You need to develop the skills to figure out how to implement the concepts such as those given in class material or in the answer above.
    – Cliff B
    Commented May 18, 2016 at 18:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .