为什么这个程序无法正确地将字符写入文件中,而是陷入无限循环?

rij*_*357 0 c file-handling while-loop

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *fp;
    char ch;

    fp = fopen("sample.txt", "r+");
    if (fp == NULL) {
        printf("Problem accessing the file!");
        exit(1);
    }

    while ((ch = fgetc(fp)) != EOF) {
        if (ch == ' ') {
            fseek(fp, -1l, SEEK_CUR);
            fputc('_', fp);
        }
    }

    fclose(fp);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在这个程序中,我希望打开的文件中的所有空白字符都替换为下划线字符。但这个程序的行为方式非常出乎意料,并陷入了无限循环。我怎样才能让它正常工作?

我尝试fp在 while 循环的每次迭代中刷新流,但它仍然没有给出预期的输出。

chq*_*lie 5

ch必须用类型定义int以容纳宏读取的所有字节值fgetc()和特殊负值EOF。

使用char使得无法EOF在您的平台上进行测试,因为类型char似乎是无符号的,因此该值在存储到 时EOF会转换为正值,这与测试中的比较不同。255chEOF

此外,您必须在从流读取切换到写入流之前发出调用(您这样做了),但也必须切换回读取fseek()(rewind()您没有这样做)。

最后,您应该以二进制方式打开文件,以便fseek正确使用绝对数字(例如-1.

这是修改后的版本:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    FILE *fp;
    int ch;

    fp = fopen("sample.txt", "rw+");
    if (fp == NULL) {
        printf("Problem accessing the file!");
        exit(1);
    }

    while ((ch = fgetc(fp)) != EOF) {
        if (ch == ' ') {
            fseek(fp, -1l, SEEK_CUR);
            fputc('_', fp);
            fseek(fp, 0L, SEEK_CUR);
        }
    }

    fclose(fp);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)