Skip to main content
gamedev.net
🔒 Locked

capture stdout from within a program?

Started by DrjonesDW3d Sep 14, 2005 at 3:23 PM 1 replies 650+ views
Original Post
DrjonesDW3d
DrjonesDW3d
I am curious if anyone knows of a way to capture everything that is being sent to stdout in a c++ program into another iostream. Mainly, so a mirrior of the output can be sent to a file. I know it's possible using a shell to save the output, but sometimes that get's confusing since programs with input won't see the output. So anyways, is there a way to attach one ostream to another or something, so that all data gets sent to one gets sent to the other (without explicitly having to tell it to send it to them both)?
Fruny
Fruny
With standard C++, you can redirect a stream by reassigning the stream buffer.
If you use Boost's new iostreams library, it is possible to use a tee device, which will send anything it receives to a pair of sinks (e.g. standard output stream and a file stream).
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
SiCrane
SiCrane
If your standard output includes non-iostream output (ex: from a library function that outputs with printf()) then one approach is to create a pipe that outputs to a child process that just a while loop that reads on standard input and outputs on standard output and to a file. Or if you're application is multi-threaded by creating a pipe that redirects standard output, then having a thread read on the pipe and outputs to standard output an a file like the child process.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.