Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C- File input/output buffers and setvbuf()

Tags:

c

file

buffer

stdio

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?

like image 372
AlexQualcosa Avatar asked Feb 07 '18 13:02

AlexQualcosa


1 Answers

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 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. 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.

like image 128
dbush Avatar answered Sep 20 '22 14:09

dbush