gpt4 book ai didi

c - getc(fp): strange character : ÿ ( at the very bottom )

转载 作者:太空宇宙 更新时间:2023-11-04 00:17:49 25 4
gpt4 key购买 nike

一个新的空文件:

touch /file.txt

阅读。打印。

fp = fopen("/file.txt", "r");
char text[1000];
int i=0;

while(!feof(fp)){
text[i++] = getc(fp);
}

text[i]='\0';

printf("%s\n", text);

结果:

ÿ

EXTRA INFO :如果 file.txt 有很多行.. 它会在它的最底部附加那个奇怪的字符。所以也许这不是在每个“while 循环”中都会发生的事情。

最佳答案

如果您使用的是 ISO 8859-15 或 8859-1 代码集,则 ÿ(带分音符的拉丁文小写字母 Y,Unicode 中的 U+00FF)的代码为 25510 或 0xFF。当您将 EOF 存储在数组中时,它会转换为 ÿ。

不要将 EOF 存储在 char 中。请记住,getchar() 返回一个 int,而不是一个 char。它必须能够返回可以存储在 unsigned char 中的每个值,加上负数的 EOF(通常但不一定是 -1)。

并且,如评论中所述,while (!feof(file)) is always wrong .这只是另一个原因。

此代码或多或少是固定的。如果无法打开文件,它确实应该报告错误。请注意,它还可以确保您不会溢出缓冲区。

FILE *fp = fopen("/file.txt", "r");
if (fp != 0)
{
char text[1000];
int i=0;
int c;
while ((c = getc(fp)) != EOF && i < sizeof(text)-1)
text[i++] = c;

text[i]='\0';

printf("%s\n", text);
fclose(fp);
}

另见 while ((c = getc(file)) != EOF) loop won't stop executing .

关于c - getc(fp): strange character : ÿ ( at the very bottom ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44690922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com