Tie for text file reading reads the last line twice

1

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 would like to know why the program prints the last line twice and how it would solve it.

    
asked by anonymous 17.01.2018 / 01:33

1 answer

4

The problem is in the while test:

while(!feof(arq)){

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

  

This indicator is usually 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 that point. >

Translating

  

This flag is enabled by a previous stream operation that attempted 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 causes the last reading to read the 3 that leaves the file at the end, but then retrying to read, and only then activates the end-of-file indicator, then showing% / p>

To fix change your 3 to:

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

So check the while return if you could read a number and only then make the impression on the screen.

    
17.01.2018 / 01:46