C- File input/output buffers and setvbuf()
用C语言,fopen()是否真的创建两个缓冲区,一个用于输入,另一个用于输出?
这就是我的C书所说的:
Normally, the first step in using standard I/O is to use f open ( ) to
open a file. (Recall, however, that the stdin, stdout, and stderr
files are opened automatically.) The fopen( ) function not only opens
a file but sets up a buffer (two buffers for read-write modes), and it
sets up a data structure containing data about the file and ..
如果使用fopen()打开文件,则会以" a +"之类的写入模式创建两个缓冲区,即读取和写入
setvbuf()函数引用哪个缓冲区?
无论打开的文件是用于读取,写入还是同时打开,打开的文件都只有一个缓冲区。
C标准的7.21.5.3节详细介绍了
7 When a file is opened with update mode (
+ as the second or third character in the above list of mode argument values), both input
and output may be performed on the associated stream. However, output
shall not be directly followed by input without an intervening call to
thefflush function or to a file positioning function (fseek ,
fsetpo s, 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. Opening (or
creating) a text file with update mode may instead open (or create) a
binary stream in some implementations.
上一段指出,在执行输入之前(必须通过定位函数显式或隐式)必须清空输出缓冲区,而在输入之后执行输出时也必须刷新。这是只有一个缓冲区的结果。
从逻辑的角度来看,这也是有意义的,因为它可以防止读写操作对文件内容产生不一致的看法。
what buffer does the
setvbuf () function refer to?
"两个都。不需要调用
C标准隐式支持单个缓冲区。根据7.21.5.3
When a file is opened with update mode (
'+' as the second
or third character in the above list of mode argument values),
both input and output may be performed on the associated
stream. However, output shall not be directly followed by
input without an intervening call to thefflush 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. Opening (or creating) a text file
with update mode may instead open (or create) a binary stream in some
implementations.
该段的要求允许使用单个缓冲区。