Is there a way to execute a callback function, or otherwise call a predefined function whenever data is written to a standard stream such as stderr or stdout? Ideally, this could be used to allow an application to output as normal with printf in the case of stdout or fprintf for other FILE streams, and conditionally perform additional tasks such as assert dependent on current settings. This could have the benefit of automatically triggering this error handling code when other libraries output to the stream.
I know that output to stderr and stdout can be redirected to other FILE handles using std::freopen. Is it practical to implement an alternate FILE stream which provides this behavior, or would that require re-implementing a great deal of standard library functions?
Standards-compliant C++ suggestions (including C++11) would be preferred, although I would be open to Windows only solutions if necessary.
I’ve since had an attempt at implementing a streambuffer as suggested by doomster, with a little help from Filtering Streambufs by James Kanze. Unless any other suggestions come up, it seems like this is the closest you can get to the original suggestion. It won’t intercept C-style output, which I suspect that is either impossible or at impractical, but it otherwise provides all the functionality I wanted.
You can replace the streambuffer in order to intercept any output to those streams, see the rdbuf() function. I think you only need to implement the overflow() function in the streambuffer class.