Redirect a copy of std :: cout to a file

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

// redirecting cout 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 streambuf psbuf = filestr.rdbuf(); // get file streambuf cout.rdbuf(psbuf); // assign streambuf to cout cout << "This is written to the file"; cout.rdbuf(backup); // restore cout original streambuf filestr.close(); return 0; } 

then I write a line to a file, but I don’t see anything in the console. How can i do this?

+6
source share
3 answers

The easiest way is to 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 perfect link for this code in action: http://ideone.com/T5Cy1M I currently cannot verify the file output is correct, although this should not be a problem.

+11
source

You can also use boost::iostreams::tee_device . See C ++ "hello world" Example Boost tee sample program .

+3
source

Your code does not work because it streambuf determines where the output written to the stream ends, and not the stream itself.

In C ++, there are no streams or streambufs that support directing output to multiple destinations, but you can write them yourself.

+1
source

All Articles