I want to create a new FILE* associated with stdout, using setvbuf()
to change its buffer behaviour to _IONBF, but I don't want to change the behaviour of stdout, since the other part of the program could still use it.
The man page of dup()
said that:
After a successful return, the old and new file descriptors may be used interchangeably.
It seems that if I change the behaviour of the new FILE*, the old stdout would also be affected. So I am wondering, how to implement it properly?
if I change the behaviour of the new FILE*
The premise of your question is false. dup
doesn't create a new
FILE *
.
dup
duplicates a file descriptor, but stdout
is a stream.
Furthermore, file descriptors have no buffer. You can't possibly change the buffering behaviour of a duplicated file descriptor.
I want to create a new FILE* associated with stdout,
To create a new stream associated with the same file descriptor as the stream stdout
, you can use
fdopen( fileno( stdout ), ... )
The code I showed above creates a new stream. setvbuf
affects a stream's buffer. Changing the new stream's buffering will have no effect on stdout
(and changing stdout
's buffering will have no effect on the new stream).