为什么要额外的'ÿ'在 C 中写入 .txt 文件时添加?
我到处都在搜索这个问题,但是建议的解决方案对我有用。
char currentChar;
FILE *fp_read = fopen("../input.txt", "r");
FILE *fp_write = fopen("../textArranged.txt", "w");
while (!feof(fp_read)){
currentChar = fgetc(fp_read);
...
}
我试图更改WARE条件(使用GetC()),但它不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
feof()
似乎在读取文件的最后一个字节后返回0
。1
afterfgetc()
已经尝试在文件末尾读取一个字节。当
fgetc()
尝试在文件末尾读取数据时,fgetc()
返回-1
。如果执行
fputc(x, ...)
并且x
不在0...255
范围内,则fputc( )
实际上会写入字节(x & 0xFF)
。在几乎所有现代计算机上,
(-1 & 0xFF)
是0xFF
,它等于字符'ÿ'
。因此会发生以下情况:
fgetc()
读取文件的最后一个字节fputc()
写入该字符feof()
返回0
,因为您尚未尝试读取文件末尾之后的字节。fgetc()
,并且由于没有剩余字节,fgetc()
返回-1
。fputc(-1, ...)
来写入字符'ÿ'
。feof()
返回1
,因为fgetc()
已尝试读取文件末尾后的字节。feof()
seems to return0
after reading the last byte of the file. It returns1
afterfgetc()
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, ...)
andx
is not in the range0...255
,fputc()
will actually write the byte(x & 0xFF)
.On nearly all modern computers,
(-1 & 0xFF)
is0xFF
which equals the character'ÿ'
.So the following happens:
fgetc()
fputc()
feof()
returns0
because 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()
returns1
becausefgetc()
already tried to read bytes after the end of the file.