From the man page of scanf
family of functions,
The value EOF
is returned if the end of input is reached before
either the first successful conversion or a matching failure occurs.
EOF
is also returned if a read error occurs, in which case the error
indicator for the stream is set, and errno
is set to indicate the
error.
This means that the last successful fscanf
call reads the last line from the stream file
after which the while
loop condition !feof(file)
is true because the end of file condition is not met yet. This means the loop is executed one extra time and the previous value of the variable number
is printed again.
Please read this - while(!feof(file))
is always wrong
You should check the return value of scanf
instead of checking the end of file indicator on the file stream.
#include <stdio.h>
int main(void) {
int number;
FILE *file = fopen("num.txt", "r");
// check file for NULL in case there
// is error in opening the file
if(file == NULL) {
printf("error in opening file\n");
return 1;
}
// check if fscanf call is successful
// by checking its return value for 1.
// fscanf returns the number of input
// items successfully matched and assigned
while(fscanf(file, "%d", &number) == 1)
printf("%d\n", number);
return 0;
}