gpt4 book ai didi

c - feof 错误的循环在 c 中

转载 作者:太空狗 更新时间:2023-10-29 15:20:35 24 4
gpt4 key购买 nike

我使用下面的代码从文件中读取一个字符并将其替换为另一个,但是我在文件末尾有一个错误。

怎么了?

我在 linux (netbeans IDE) 上测试了这段代码,它是正确的并且运行良好,但是当我尝试在 windows 中使用 VS 2008 时,我发现了一个非结束循环。

//address = test.txt

FILE *fp;
fp=fopen(address,"r+");
if(fp == 0)
{
printf("can not find!!");
}
else
{
char w = '0'; /// EDIT : int w;
while(1)
{
if((w = fgetc(fp)) != EOF)
{
if((w = fgetc(fp)) != EOF)
{
fseek(fp,-2,SEEK_CUR);
fprintf(fp,"0");
}
}
else
{
break;
}
}
}
fclose(fp);

最佳答案

您正在存储 fgetc 的结果在 char 中,而不是 int。

char w = '0'; /* Wrong, should be int. */

顺便说一下,C FAQ 中提到了这个问题。 .

If type char is unsigned, an actual EOF value will be truncated (by having its higher-order bits discarded, probably resulting in 255 or 0xff) and will not be recognized as EOF, resulting in effectively infinite input.

编辑

再次阅读您的问题,您寻找两个字符并写一个字符的方式非常可疑。这很可能会导致无限循环。

EDIT2

您(可能)想要这样的东西(未经测试):

while ((w = getc(fp)) != EOF) {
fseek(fp, -1, SEEK_CUR);
fprintf(fp, "0");
fflush(fp); /* Apparently necessary, see the answer of David Grayson. */
}

关于c - feof 错误的循环在 c 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6633534/

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