首页 > 解决方案 > 为什么 fflush 不允许我的程序切换模式?

问题描述

我有以下 C 应用程序:

#include <stdio.h>
int main() {
    // Create a file.
    FILE *filePointer = fopen("deleteme.txt", "w+");
    if (filePointer == NULL) {
        printf("Operation failed.\n");
        return 0;
    }
    // Write "Test" to the file.
    if (fputs("Test", filePointer) == EOF) {
        printf("Operation failed.\n");
        return 0;
    }
    // Seek to the beginning.
    if (fseek(filePointer, 0, SEEK_SET) != 0) {
        printf("Operation failed.\n");
        return 0;
    }
    // Read the character "T".
    if (fgetc(filePointer) == EOF) {
        printf("Operation failed.\n");
        return 0;
    }
    // Flush streams.
    fflush(filePointer);
    // Write "esting" to the file.
    if (fputs("esting", filePointer) == EOF) { // <--- Fails here.
        printf("Operation failed.\n");
        return 0;
    }
    printf("Operation succeeded.\n");
    return 0;
}

我在 Windows 操作系统下运行它:

我上面链接的代码在调用fputs("esting", filePointer). 这是为什么?在线查看文档,它说:

在为更新而打开的文件中(即为读取和写入而打开),流应在输出操作之后刷新,然后再执行输入操作。这可以通过重新定位(fseek、fsetpos、rewind)或显式调用 fflush 来完成

正如您在上面的代码中看到的那样,由于我已经在更新模式下打开了文件w+,所以我在调用fflush之前显式调用fputs。我希望这可以让我切换模式,以便我可以在阅读后执行写入,还是我误解了文档?我知道如果我fflush用调用替换上面的代码将起作用fseek(交换似乎可以解决这个问题),但是为什么它在使用时不起作用?fflushfseek(filePointer, 0, SEEK_CUR)fflush

标签: cwindowsgccvisual-studio-codemingw

解决方案


推荐阅读