What is the advantage or in what situation would it be useful to use the functions setvbuf()
or setbuf()
in the ANSI C language?
It happens that I have read the theory and I have experimented with the functions, but I do not notice a difference between specifying the buffer or letting the system manage it automatically (that is, without using setvbuf()
or setbuf()
).
Thank you very much in advance for your answers.
Taking the console output as a reference, When you try to print something, for example with
printf
, the text is not displayed immediately on the console but is stored in an intermediate buffer.This buffer exists for several reasons:
Well, if you set the buffer size too small, then the buffer would fill up quickly and this would force more screen refreshes than necessary, penalizing your performance. On the other hand, using a buffer that is too large has an impact on the available memory in the equipment, which would be reduced unnecessarily.
Between the terms "too big" and "too small" there is a whole range of possibilities in which the benefit between using one size or another is variable.
These functions can be explained under certain contexts, such as embedded systems or systems with very limited resources, or a computer that uses a certain output device that, due to its characteristics, only works well with a buffer of a certain size, etc. That is, environments in which the use of resources must be optimized to the maximum (let's not forget that C is a multipurpose language). Of course, in normal conditions there is no need to play with these functions since you are hardly going to obtain an obvious improvement playing with the values of the buffer size.