Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect stdout/stderr to a string

Tags:

c++

c

stdout

stderr

there has been many previous questions about redirecting stdout/stderr to a file. is there a way to redirect stdout/stderr to a string?

like image 584
Prasanth Madhavan Avatar asked Mar 24 '11 12:03

Prasanth Madhavan


1 Answers

Yes, you can redirect it to an std::stringstream:

std::stringstream buffer; std::streambuf * old = std::cout.rdbuf(buffer.rdbuf());  std::cout << "Bla" << std::endl;  std::string text = buffer.str(); // text will now contain "Bla\n" 

You can use a simple guard class to make sure the buffer is always reset:

struct cout_redirect {     cout_redirect( std::streambuf * new_buffer )          : old( std::cout.rdbuf( new_buffer ) )     { }      ~cout_redirect( ) {         std::cout.rdbuf( old );     }  private:     std::streambuf * old; }; 
like image 103
Björn Pollex Avatar answered Oct 06 '22 17:10

Björn Pollex