Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting stdout from another program in C++

Tags:

c++

stdout

I'm writing a unit test and therefore, cannot change the code within the file that I'm testing. The code that I'm testing has messages in cout that I am trying to redirect into a file to check to make sure that the program is outputting the right messages. Does anyone have a way to redirect stdout in another program that won't cause a lag? I have tried freopen() and that causes my program to hang for some reason.

like image 845
Annika Peterson Avatar asked Dec 28 '25 21:12

Annika Peterson


1 Answers

You could create a filebuf then replace cout's streambuf with it:

{
  std::filebuf f;
  f.open("output.txt", std::ios::out);
  std::streambuf* o = std::cout.rdbuf(&f);
  std::cout << "hello" << std::endl;  // endl will flush the stream
  std::cout.rdbuf(o);
}

You need to restore cout's original streambuf again (or set it to a null pointer) or it will probably crash when the global streams are flushed and destroyed, because the filebuf will already have gone out of scope.

like image 142
Jonathan Wakely Avatar answered Dec 31 '25 12:12

Jonathan Wakely