-1

I searched about this problem everywhere, but none of the suggested solutions worked for me.

char currentChar;
FILE *fp_read = fopen("../input.txt", "r");
FILE *fp_write = fopen("../textArranged.txt", "w");
while (!feof(fp_read)){
      currentChar = fgetc(fp_read);
      ...
}

I tried to change the while condition (using getc()), but it didn't work.

  • 3
    see [Why is `while ( !feof (file) )` always wrong?](https://stackoverflow.com/q/5431941/995714) – phuclv Apr 03 '22 at 10:28
  • 1
    Just a recommendation: write first to a buffer then write to the file. Currently you are writing every single byte on its own. – cediwelli Apr 03 '22 at 10:29
  • 1
    disks are block devices so reading block-by-block is much more efficient – phuclv Apr 03 '22 at 10:30
  • 2
    Do `fopen` with `"rb"` and `"wb"` for binary mode. And `fgetc` returns `int`. – i486 Apr 03 '22 at 10:30
  • 'ÿ' is character code 0xff, what remains of EOF when the code truncates it by storing it in a char. In other words, fgetc() tried to tell you that it encountered the end of the file, but it got copied to the output file instead. – Hans Passant Apr 03 '22 at 12:46
  • 1
    see [Why does `fgetc()` return int instead of char?](https://stackoverflow.com/q/49063518/995714) – phuclv Apr 03 '22 at 12:48

1 Answers1

3

feof() seems to return 0 after reading the last byte of the file. It returns 1 after fgetc() already made the attempt to read one more byte after the end of the file.

When fgetc() makes the attempt to read data after the end of the file, fgetc() returns -1.

If you perform fputc(x, ...) and x is not in the range 0...255, fputc() will actually write the byte (x & 0xFF).

On nearly all modern computers, (-1 & 0xFF) is 0xFF which equals the character 'ÿ'.

So the following happens:

  • ...
  • Your program reads the last byte of the file using fgetc()
  • It writes that character using fputc()
  • Although there are no more bytes left in the file, feof() returns 0 because you did not make the attempt to read bytes after the end of the file, yet.
  • Your program calls fgetc() and because there are no more bytes left, fgetc() returns -1.
  • Your program calls fputc(-1, ...) which writes the character 'ÿ'.
  • feof() returns 1 because fgetc() already tried to read bytes after the end of the file.
Martin Rosenau
  • 17,897
  • 3
  • 19
  • 38