繁体   English   中英

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

[英]Redirect the copy of std::cout to the file

我需要将 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++ 没有任何支持将输出定向到多个目的地的流或流缓冲,但您可以自己编写一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM