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


What is the advantage or in which 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 difference between specifying the buffer or letting the system manage it automatically (ie without using setvbuf() or setbuf() ).

Thank you in advance for your answers.

asked by Jose Alberto Rosa Mañan 17.08.2018 в 02:17

1 answer


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

This buffer exists for several reasons:

  • Avoid blinking in the console, if the console were updated with each character and line break, there would be unpleasant effects (as if the contents of the console were flowing or blinking)
  • Improve performance. The most costly operation of this process is to update the contents of the console. Reducing the number of times it refreshes 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 make more screen refreshments than necessary, penalizing your performance. On the other hand, using too large a buffer has an impact on the available memory in 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 have their explanation under certain contexts, such as embedded systems or with very limited resources, or a team that makes use of 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 we must maximize the use of resources (do not forget that C is a multipurpose language). Of course, under 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 size of the buffer.

answered by 17.08.2018 / 07:50