Loop for reading text file reads the last line twice

Asked

Viewed 313 times

2

I’m doing a test to read a simple txt file with three numbers:

1

2

3

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

int main() {   
  int conta;
  FILE* arq = fopen("dicionario.txt", "r");

  if(arq!=NULL){
    while(!feof(arq)){
      fscanf(arq, "%d", &conta);
      printf("%d\n", conta);
    }
  }

  fclose(arq); 
  return 0;
}

I wonder why the program prints the last line twice and how it would solve this.

  • with this change in the loop works normally:char c while((c = getc(Arq) ) != EOF). But still do not understand the pq of the first print twice the last line :/

  • 1

    Caio, avoid using the c++ tag in questions about C. The two languages are quite different.

1 answer

5


The problem is in the test of while:

while(!feof(arq)){

That actually tests whether any reading has been made beyond the end, like the documentation indicates

This Indicator is generally set by a Previous Operation on the stream that attempted to read at or Past the end-of-file.

Notice that stream’s Internal position Indicator may point to the end-of-file for the next Operation, but still, the end-of-file Indicator may not be set until an Operation Attempts to read at that point.

Translating

This indicator is activated by a previous operation in the stream you tried to read beyond the end of the file.

Note that the internal position of the stream may be pointing to the end of the file for the next operation, but still, the end of file indicator will not be activated until a read is made.

This makes the last reading read the 3 which leaves the file at the end, but then tries to read again and only then activates the end of file indicator, showing then twice the 3.

To correct change your while for:

while(fscanf(arq, "%d", &conta) == 1) {
    printf("%d\n", conta);
}

So check for the return of fscanf if managed to read a number and only in this case makes the impression on the screen.

  • Got it! It worked, thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.