In C language, does fopen() really creates two buffers, one for input and the other for output?
This is what my C book says:
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 ..
If opening a file with fopen () creates two buffers, in a writing mode like "a+", ie both reading and writing
FILE * fp = fopen ("file.txt", "a +");
setvbuf (destination_file, NULL, _IOFBF, BUFFER_SIZE);
what buffer does the setvbuf () function refer to?
An open file only has a single buffer, regardless of whether it was opened for reading, writing, or both.
Section 7.21.5.3 of the C standard, which details the fopen
function, states:
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.
The above paragraph states the output buffer must be flushed before performing input (either explicitly or implicitly via a positioning function), and the same when performing output after input. This is a consequence of having only a single buffer.
This also makes sense from a logical point of view as it prevents reads and writes from having an inconsistent view of the file contents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With