Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect the copy of std::cout to the file

Tags:

c++

I need redirect the copy of std::cout to the file. I.e. I need see the output in console, and in file. If I use this:

// redirecting cout's output
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  streambuf *psbuf, *backup;
  ofstream filestr;
  filestr.open ("c:\\temp\\test.txt");

  backup = cout.rdbuf();     // back up cout's streambuf

  psbuf = filestr.rdbuf();   // get file's streambuf
  cout.rdbuf(psbuf);         // assign streambuf to cout

  cout << "This is written to the file";

  cout.rdbuf(backup);        // restore cout's original streambuf

  filestr.close();

  return 0;
}

then I write string to the file, but I see the nothing in console. How can I do it?

like image 316
Andrey Bushman Avatar asked Jan 04 '13 10:01

Andrey Bushman


1 Answers

The simplest you can do is create an output stream class that does this:

#include <iostream>
#include <fstream>

class my_ostream
{
public:
  my_ostream() : my_fstream("some_file.txt") {}; // check if opening file succeeded!!
  // for regular output of variables and stuff
  template<typename T> my_ostream& operator<<(const T& something)
  {
    std::cout << something;
    my_fstream << something;
    return *this;
  }
  // for manipulators like std::endl
  typedef std::ostream& (*stream_function)(std::ostream&);
  my_ostream& operator<<(stream_function func)
  {
    func(std::cout);
    func(my_fstream);
    return *this;
  }
private:
  std::ofstream my_fstream;
};

See this ideone link for this code in action: http://ideone.com/T5Cy1M I can't currently check if the file output is done correctly though it shouldn't be a problem.

like image 193
rubenvb Avatar answered Oct 09 '22 00:10

rubenvb