c中错误的循环

mim*_*mad 4 c feof

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

怎么了?

我在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);
Run Code Online (Sandbox Code Playgroud)

cni*_*tar 6

您将结果存储fgetc在char中,而不是int.

char w = '0'; /* Wrong, should be int. */
Run Code Online (Sandbox Code Playgroud)

顺便提一下,这个问题在C FAQ中提到.

如果type charunsigned,则实际的EOF值将被截断(通过丢弃其高阶位,可能导致255或0xff)并且不会被识别为EOF, 从而导致无限输入.

编辑

再次阅读你的问题,你寻找两个角色并写一个角色的方式非常可疑.这很可能导致无限循环.

EDIT2

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

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