Reputation: 21
Currently the first thing I do before I print anything in my program is run setbuf(stdout, _IOFBF);
However printf("hello\n");
will still flush the buffer.
This is bad, I want to control when it sends all its text (In the interest of creating a "smooth" animated gif experience with ascii text in the terminal).
How can I tell my program I would like stdout
to be fully buffered?
Upvotes: 2
Views: 1242
Reputation: 144740
You cannot use setbuf
this way: setbuf(stdout, _IOFBF);
. The second argument is a pointer to an array of BUFSIZ
bytes.
You should instead use setvbuf()
with a potentially larger buffer size before you perform any output:
setvbuf(stdout, NULL, _IOFBF, 4096);
You can pass an actual array instead of NULL
but it is not necessary as setvbuf
will allocate the buffer if you don't and might still do that if you do. You may want to check the return value to ensure the call succeeded. If for some unexpected reason this call fails on your system, the output would not be fully buffered.
Here is the C Standard definition:
7.21.5.6 The
setvbuf
functionSynopsis
#include <stdio.h> int setvbuf(FILE * restrict stream, char * restrict buf, int mode, size_t size);
The
setvbuf
function may be used only after the stream pointed to bystream
has been associated with an open file and before any other operation (other than an unsuccessful call tosetvbuf
) is performed on the stream. The argumentmode
determines howstream
will be buffered, as follows:_IOFBF
causes input/output to be fully buffered;_IOLBF
causes input/output to be line buffered;_IONBF
causes input/output to be unbuffered. Ifbuf
is not a null pointer, the array it points to may be used instead of a buffer allocated by thesetvbuf
function and the argumentsize
specifies the size of the array; otherwise,size
may determine the size of a buffer allocated by thesetvbuf
function. The contents of the array at any time are indeterminate.Returns
The
setvbuf
function returns zero on success, or nonzero if an invalid value is given formode
or if the request cannot be honored.
Upvotes: 4
Reputation: 126203
You need to use setvbuf
to set the buffer mode, size, and location:
buffer = malloc(1024);
setvbuf(stdout, buffer, _IOFBF, 1024);
You need to ensure your buffer is large enough that it will never flush due to capacity if you want total control over flushing.
Upvotes: 0