Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

c++ - Redirect the copy of std::cout to the file

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...