C r+的问题;fopen()中的模式

C r+的问题;fopen()中的模式,c,file-io,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,

我在尝试用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;
}
它给我相同的输出。那么,我为什么能够在没有输出流上的
fflush()
的情况下进行写入?(我在输出流上写入
fputc()
是正确的吗?)此外,我是否可以在上述代码片段中使用
fflush()
而不是
fseek()

使用更新模式打开文件时。。。输出不应为空 直接后跟输入,无需调用
fflush
功能或文件定位功能(
fseek
fsetpos
倒带
),输入后不得直接跟随输出 对文件定位函数的中间调用,除非输入 操作遇到文件结尾

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


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

谢谢!这澄清了很多。此外,我们编写的任何内容(如
fputc()
)都发生在输出流上,对吗?您的想法是正确的,但从技术上讲,当您使用
r+
打开时,您在这里有一个更新流,而不是单独的输出流和输入流。类似于
fputc()
的函数将输出到更新流,类似于
fgetc()
的函数将从更新流获取输入。再次感谢!非常有用。
/* write something */
fseek( fp, -1, SEEK_CUR );
fputc( 'x', fp );
//fflush(fp);