Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the point of using the setvbuf() function in c?

Tags:

c

Why would you want to set aside a block of memory in setvbuf()?

I have no clue why you would want to send your read/write stream to a buffer.

like image 219
Kit Fox Avatar asked Jun 17 '13 00:06

Kit Fox


People also ask

What does setvbuf do in C?

The setvbuf function allows the program to control both buffering and buffer size for stream . stream must refer to an open file that has not undergone an I/O operation since it was opened.

When to use setvbuf?

You can use setvbuf to supply your own buffer, or make the file operations completely unbuffered (like to stderr is). It can be used to create fmemopen functionality on systems that doesn't have that function.

What is the use of Setbuf in C?

setbuf() — Control Buffering If the operating system supports user-defined buffers, setbuf() controls buffering for the specified stream. The setbuf() function only works in ILE C when using the integrated file system. The stream pointer must refer to an open file before any I/O or repositioning has been done.

What is line buffer in C?

Line buffering - characters are transmitted to the system as a block when a new-line character is encountered. Line buffering is meaningful only for text streams and UNIX file system files. Full buffering - characters are transmitted to the system as a block when a buffer is filled.


1 Answers

setvbuf is not intended to redirect the output to a buffer (if you want to perform IO on a buffer you use sprintf & co.), but to tightly control the buffering behavior of the given stream.

In facts, C IO functions don't immediately pass the data to be written to the operating system, but keep an intermediate buffer to avoid continuously performing (potentially expensive) system calls, waiting for the buffer to fill before actually performing the write.

The most basic case is to disable buffering altogether (useful e.g. if writing to a log file, where you want the data to go to disk immediately after each output operation) or, on the other hand, to enable block buffering on streams where it is disabled by default (or is set to line-buffering). This may be useful to enhance output performance.

Setting a specific buffer for output can be useful if you are working with a device that is known to work well with a specific buffer size; on the other side, you may want to have a small buffer to cut down on memory usage in memory-constrained environments, or to avoid losing much data in case of power loss without disabling buffering completely.

like image 78
Matteo Italia Avatar answered Nov 15 '22 20:11

Matteo Italia