4

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

怎么了?

我在 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);
4

2 回答 2

6

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

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

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

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

编辑

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

编辑2

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

while ((w = getc(fp)) != EOF) {
    fseek(fp, -1, SEEK_CUR);
    fprintf(fp, "0");
    fflush(fp); /* Apparently necessary, see the answer of David Grayson. */
}
于 2011-07-09T08:04:53.137 回答
3

cplusplus.com 上的fopen 文档说:

对于允许读取和写入(或附加)的模式(包括“+”号的模式),应在读取操作之后刷新流(fflush)或重新定位(fseek、fsetpos、rewind)写操作或写操作后跟读操作。

我们可以在fflush之后添加一个调用fprintf来满足该要求。

这是我的工作代码。它创建一个名为的文件example.txt,在程序退出后,该文件的内容将是000000000000n.

#include <stdio.h>

int main(int argc, char **argv)
{
    FILE * fp;
    int w;

    fp = fopen("example.txt","w");
    fprintf(fp, "David Grayson");
    fclose(fp);

    fp = fopen("example.txt","r+");
    while(1)
    {
        if((w = fgetc(fp)) != EOF)
        {
            if((w = fgetc(fp)) != EOF)
            {
                fseek(fp,-2,SEEK_CUR);
                fprintf(fp,"0");
                fflush(fp);  // Necessary!
            }
        }
        else
        {
            break;
        }
    }
    fclose(fp);
}

这是在 Windows 中使用 MinGW 测试的。

于 2011-07-09T08:50:56.707 回答