c - fopen() 中 r+ 模式的问题

标签 c file-io

我正在尝试用 C 语言打开文件的各种模式。我对 r+、w+ 和 a+ 的模式有点卡住。

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

int main(void)
{
    .....
    /* make a file with something in it */
    if( (fp = fopen( filename, "w" )) )
    {
        fprintf( fp, "abcd" );
        fclose( fp );
    }
    /* see how r+ works */
    if( (fp = fopen( filename, "r+" )) )
    {
        int c = 0;

        /* read something */
        c = fgetc( fp );
        printf( "c is %c\n", c );

        /* write something */
        fseek( fp, -1, SEEK_CUR );
        fputc( 'x', fp );
        fflush(fp);

        /* read something */
        c = fgetc( fp );
        printf( "c is %c\n", c );

        /* rewind and show the whole thing */
        rewind( fp );
        while( (c = fgetc( fp )) != EOF )
        {
            printf( "c is %c\n", c );
        }

        fclose(fp);
    }

    return 0;
}

这给了我以下输出 -
c是一个
c是b
c是x
c是b
c就是c
c是d

即使我在这里删除了 fflush() -

/* write something */
fseek( fp, -1, SEEK_CUR );
fputc( 'x', fp );
//fflush(fp);

它给了我相同的输出。那么,为什么我能够在没有 fflush() 的情况下在输出流上写入?(我对 fputc() 在输出流上写入是否正确?)另外,我可以在上面的代码片段中使用 fflush() 而不是 fseek()

最佳答案

根据 C11 7.21.5.3.7:

When a file is opened with update mode ... output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos or rewind) and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.

标准不能保证您在没有 fflush() 调用的情况下获得相同的输入这一事实(尽管一些实现,包括 glibc,允许它,所以看到它并不奇怪在这里工作)。

对于你的另一个问题,不,你不能在这里使用 fflush() 而不是 fseek(),因为你的 fseek() 出现在输出操作之前,而不是输入操作之前。 fflush() 仅对输出流有意义,对于未输入最近操作的更新流。

关于c - fopen() 中 r+ 模式的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21373288/

相关文章:

c++ - 如何在 C 或 C++ 中进行字符串实习?

在 sysfs 中创建属性

c - 如何正确终止 pthread?

c++ - 关于使用 C++ istream_iterator 从文件中读取部分数据的一些事情

c++ - 在 C++ 中为文件 I/O 包含其他文件

无法计算大于 20 的阶乘! !怎么做呢?

c - memccpy 返回比 src 起始地址更低的内存地址

c - Malloc 失败并显示 errno 12

php - fopen 前面有/没有@

html - 是否可以在 html5 中验证 input=file 的大小和类型