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.
feof()seems to return0after reading the last byte of the file. It returns1afterfgetc()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, ...)andxis not in the range0...255,fputc()will actually write the byte(x & 0xFF).On nearly all modern computers,
(-1 & 0xFF)is0xFFwhich equals the character'ÿ'.So the following happens:
fgetc()fputc()feof()returns0because you did not make the attempt to read bytes after the end of the file, yet.fgetc()and because there are no more bytes left,fgetc()returns-1.fputc(-1, ...)which writes the character'ÿ'.feof()returns1becausefgetc()already tried to read bytes after the end of the file.