【发布时间】: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++