Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setbuf redirection

I use setbuf in order to redirect stdout to char buffer But I get some side effect after it ,when I want to write to the stdout only the new data

As explained in the following code:

#define bufSize  100
int main()
{
    char buf[bufSize];
    setbuf(stdout, buf);
    printf("123");             //123 is written to the buffer

    setbuf(stdout,NULL);       //123 is written to the stdout(unwanted side effect)
    printf("456");             //123456 appears in the stdout
}

How can I solve the problem?

Other question regarding this - will this code work for unix/linux/mac os?

Can anyone propose the solution for redirection?

like image 659
Yakov Avatar asked Jan 16 '26 23:01

Yakov


1 Answers

The setbuf() function does not redirect the output to the buffer. It just tells the standard I/O library "use this buffer; do not allocate one yourself".

You are also supposed to use setbuf() once per open stream (immediately after it is opened and before anything else is done to it) and leave well alone afterwards. If you use it multiple times, you get into undefined behaviour - and what you see is acceptable because the required behaviour is undefined.

The C99 standard says:

§7.19.5.5 The setbuf function

Except that it returns no value, the setbuf function is equivalent to the setvbuf function invoked with the values _IOFBF for mode and BUFSIZ for size, or (if buf is a null pointer), with the value _IONBF for mode.

§7.19.5.6 The setvbuf function

The setvbuf function may be used only after the stream pointed to by stream has been associated with an open file and before any other operation (other than an unsuccessful call to setvbuf) is performed on the stream.

like image 105
Jonathan Leffler Avatar answered Jan 19 '26 17:01

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!