0
char ch;
int n = 0;
FILE* fp;

fp = fopen("test.txt", "r");
while(!feof(fp)){
    n++;
    fscanf(fp, "%c", &ch);
    fprintf("%c", ch);
}
printf("%d\n", n);

test.txt below

abcd

I tried to count how many time does this while loop go by printing out integer n. I thought the result would be 4 cuz fp only contains 4 characters, "abcd". But actual result was 6. There are two newline character which is ascii code 10 before EOF.

I double-checked test.txt file and it contains no other character then abcd. Where did these 2 newline characters come from? I used vim editor.

Castle_Dust
  • 63
  • 1
  • 5

1 Answers1

2

First, don't use scanf when getc will do. Second, stop using feof as if it is magic. (Why is “while ( !feof (file) )” always wrong?). Third, "abcd\n" is 5 characters, and your misuse of feof is causing you to reuse the final newline and overcount by one.

Community
  • 1
  • 1
William Pursell
  • 204,365
  • 48
  • 270
  • 300