Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect output of an function printing to console to string

Tags:

c++

c++11

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

like image 992
pyCthon Avatar asked Oct 21 '13 02:10

pyCthon


People also ask

How do I save console output to string Java?

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!

How do I redirect printf to a file?

You can use freopen. freopen("desiredFileName", "w", stdout); Once you are done, you can undo the reassignment like this: freopen("/dev/stdout", "w", stdout);


2 Answers

@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.

like image 180
Nawaz Avatar answered Oct 22 '22 17:10

Nawaz


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";
}
like image 1
David G Avatar answered Oct 22 '22 18:10

David G