我正在尝试用 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
orrewind
) 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/