setbuf redirection

2019-08-04 09:26发布

问题:

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?

回答1:

I don't think you can redirect stdout to a buffer like this. It ends up in stdout anyway. You only specify a buffer which will be used by your stream.

If you use setbuf(stdout, NULL), it will create a new buffer behind the scenes. And it will be unbuffered writing.. i.e. no flush needed.

So there is no side effect here, just normal behaviour.


If you want to redirect stdout look here. The first two answers describe two techniques doing that.



回答2:

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.



回答3:

setbuf is not for redirection. It's largely useless except for turning off buffering so all output appears immediately. It can also be used to give stdio a different buffer it can use for the FILE, but it's not obligated to use it in any particular way, and since stdio normally uses its own buffer of a good size, I can't see how providing your own buffer could be terribly useful.

If you want to redirect output, you should probably ask a new question describing better exactly what effects you want to obtain.