将std::cout的副本重定向到文件

Redirect the copy of std::cout to the file

本文关键字:重定向 副本 文件 std cout      更新时间:2023-10-16

我需要重定向 std::cout的副本到文件。也就是说,我需要在控制台和文件中看到输出。如果我使用这个:

// 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;
}

然后我将字符串写入文件,但我在控制台中看到什么都没有。我该怎么做呢?

最简单的方法就是创建一个输出流类:

#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;
};

请参阅此ideone链接以查看此代码的实际操作:http://ideone.com/T5Cy1M我目前不能检查文件输出是否正确,虽然它不应该是一个问题。

您也可以使用boost::iostreams::tee_device。参见c++ "hello world"Boost tee示例程序为示例。

您的代码不起作用,因为是streambuf决定写入流的输出在哪里结束,而不是流本身。

c++没有任何支持将输出定向到多个目标的流或流bufs,但您可以自己编写一个。