【问题标题】:Redirect the copy of std::cout to the file将 std::cout 的副本重定向到文件
【发布时间】:2013-01-04 10:29:56
【问题描述】:

我需要将 std::cout 的副本重定向到文件。 IE。我需要在控制台和文件中查看输出。如果我使用这个:

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

然后我将字符串写入文件,但我在控制台中看不到任何内容。我该怎么做?

【问题讨论】:

  • 在外部使用tee 或类似的方法不是更容易(也许更合适)吗:unixhelp.ed.ac.uk/CGI/man-cgi?tee
  • @NPE:假设此过程在可行的上下文中运行。情况并非总是如此。
  • @NPE 当有人问起 C++ iostreams 你用 UNIX 特定的 C 函数回答?
  • 我现在用的是Windows操作系统。

标签: c++


【解决方案1】:

您可以做的最简单的事情是创建一个输出流类来执行此操作:

#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 我目前无法检查文件输出是否正确完成,尽管这应该不是问题。

【讨论】:

    【解决方案2】:

    您也可以使用boost::iostreams::tee_device。示例见C++ "hello world" Boost tee example program

    【讨论】:

    • 我尝试在 Visual Studio 中使用您的代码,但此 IDE 不知道此类标头。 :(
    • @Bush 你需要安装和设置boost(见www.boost.org),或者使用不需要boost的方法。
    【解决方案3】:

    您的代码不起作用,因为是 streambuf 决定了写入流的输出的最终位置,而不是流本身。

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

    【讨论】:

    • >您的代码不起作用,因为它是 streambuf 决定了写入流的输出的最终位置,而不是流本身。 *** 不,此代码在 Windows 上运行良好。我是从cplusplus.com/reference/ios/ios/rdbuf 页面获得的。
    • @Bush:从某种意义上说它不起作用,因为它没有做你想做的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2012-06-16
    相关资源
    最近更新 更多