7

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?

Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182

3 Answers3

12

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.

rubenvb
  • 74,642
  • 33
  • 187
  • 332
3

You could also use boost::iostreams::tee_device. See C++ "hello world" Boost tee example program for an example.

Community
  • 1
  • 1
Anders Johansson
  • 3,926
  • 19
  • 19
1

Your code does not work, because it is the streambuf that determines where the output written to a stream end up, not the stream itself.

C++ does not have any streams or streambufs that support directing the output to multiple destinations, but you could write one yourself.

Bart van Ingen Schenau
  • 15,488
  • 4
  • 32
  • 41
  • >Your code does not work, because it is the streambuf that determines where the output written to a stream end up, not the stream itself. *** No, this code works fine on Windows. I have got it from the http://www.cplusplus.com/reference/ios/ios/rdbuf/ page. – Andrey Bushman Jan 04 '13 at 11:03
  • @Bush: It does not work in the sense that it does not do what you would like it to do. – Bart van Ingen Schenau Jan 04 '13 at 14:18