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?
I don’t think you can redirect
stdoutto a buffer like this. It ends up instdoutanyway. 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
stdoutlook here. The first two answers describe two techniques doing that.