What is the point of using setvbuf or setbuf in ansiC?


What is the advantage or in what situation would it be useful to use the setvbuf() or setbuf() in the ANSI C language?

It happens that I have read the theory and have experimented with the functions, but I don't 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 responses.


Taking the console output as a reference, when you try to print something, for example with printf , the text is not immediately displayed on the console but is stored in an intermediate buffer.

This buffer exists for several reasons:

  • Avoid flickering on the console, if the console is updated with each character and line break, it will produce unpleasant effects (as if the content of the console flows or flickers)
  • Improve performance. By far the most expensive operation in this process is updating the contents of the console. Reducing the number of times it is refreshed greatly improves the performance of the application.

Well, if you set a buffer size too small, then it would fill up quickly and this would force you to refresh the screen more than necessary, penalizing your performance. On the other hand, using a buffer that is too large has an impact on the memory available on the computer, which would be unnecessarily reduced.

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 are explained under certain contexts, such as embedded systems or with very limited resources, or a device that makes use of a specific output device that, due to its characteristics, only works well with a certain size buffer, etc. In other words, 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 will hardly get an obvious improvement by playing with the values ​​of the buffer size.

Scroll to Top