我需要将 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;
}
我将字符串写入文件,但在控制台上看不到任何内容。该怎么办?
tee
或类似工具在外部处理这个操作可能更简单(而且也许更合适)。详见:http://unixhelp.ed.ac.uk/CGI/man-cgi?tee - NPE