Home > Article > Backend Development > How to Redirect C STDOUT to a User-Defined Function?
Redirecting C STDOUT to a Custom Function
Redirecting stdout to a file is a common practice, but what if you want to redirect it to a function you define?
For example, consider the following hypothetical case:
<code class="cpp">void MyHandler(const char* data); // <Magical redirection code> printf("test"); std::cout << "test" << std::endl; // MyHandler should have been called with "test" twice at this point</code>
Solution
As pointed out by @Konrad Rudolph, redirecting stdout to a function is possible using an ostringstream. Here's how you can do it:
<code class="cpp">// Redirect cout. std::streambuf* oldCoutStreamBuf = std::cout.rdbuf(); std::ostringstream strCout; std::cout.rdbuf(strCout.rdbuf()); // This goes to the string stream. std::cout << "Hello, World!" << std::endl; // Restore old cout. std::cout.rdbuf(oldCoutStreamBuf); // Will output our Hello World! from above. std::cout << strCout.str();</code>
While this method works for cout, cerr, and clog, it may not redirect all stdout for functions like printf, which typically target both stdout and stderr streams.
For larger data, more advanced techniques like freopen(), setbuf(), dup(), and dup2() can be employed. These operations require a bit more system-level understanding and may involve creating pipes or manipulating file descriptors.
The above is the detailed content of How to Redirect C STDOUT to a User-Defined Function?. For more information, please follow other related articles on the PHP Chinese website!