lets say we have a function which prints text to the console and in which we do not have control over the source but we are able to call it. For example
void foo() {
std::cout<<"hello world"<<std::endl;
print_to_console(); // this could be printed from anything
}
is it possible to redirect the output of the above function to a string without changing the function itself?
I'm not looking for a way to do this via terminal
If you create a PrintStream connected to a ByteArrayOutputStream , then you can capture the output as a String . Example: // Create a stream to hold the output ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); // IMPORTANT: Save the old System. out!
You can use freopen. freopen("desiredFileName", "w", stdout); Once you are done, you can undo the reassignment like this: freopen("/dev/stdout", "w", stdout);
@Andre asked in the comment of my first answer:
What happens if they used printf, puts, write, etc ? – Andre Kostur
For printf
, I came up with the following solution. It will work only on POSIX as fmemopen is available on POSIX only, but you can use temporary file instead if you want to — that will be better if you want a portable solution. The basic idea will be same.
#include <cstdio>
void print_to_console() {
std::printf( "Hello from print_to_console()\n" );
}
void foo(){
std::printf("hello world\n");
print_to_console(); // this could be printed from anything
}
int main()
{
char buffer[1024];
auto fp = fmemopen(buffer, 1024, "w");
if ( !fp ) { std::printf("error"); return 0; }
auto old = stdout;
stdout = fp;
foo(); //all the std::printf goes to buffer (using fp);
std::fclose(fp);
stdout = old; //reset
std::printf("<redirected-output>\n%s</redirected-output>", buffer);
}
Output:
<redirected-output>
hello world
Hello from print_to_console()
</redirected-output>
Online Demo.
class buffer
: public std::streambuf
{
public:
buffer(std::ostream& os)
: stream(os), buf(os.rdbuf())
{ }
~buffer()
{
stream.rdbuf(buf);
}
private:
std::ostream& stream;
std::streambuf* buf;
};
int main()
{
buffer buf(std::cout);
std::stringbuf sbuf;
std::cout.rdbuf(sbuf);
std::cout << "Hello, World\n";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With