使用cout或cerr在重定向到文件后输出到控制台
问题描述:
将cout或cerr重定向到文件是很容易的。我可以使用它将第三方输出重定向到一个文件。但是,在我将第三方输出重定向到一个文件后,如何使用cout自己输出到控制台?
Redirecting cout or cerr to a file is easy enough. I can use this to redirect third party output to a file. However, after I have redirected the third party output to a file, how do I then use cout myself to output to the console?
答
p>我是RAII的好粉丝,所以我曾经写过这个小帮手类。它将重定向流,直到它超出范围,此时它恢复原始缓冲区。相当方便。 :)
I'm a great fan of RAII, so I once wrote this small helper class. It will redirect the stream until it goes out of scope, at which point it restores the original buffer. Quite handy. :)
class StreamRedirector {
public:
explicit StreamRedirector(std::ios& stream, std::streambuf* newBuf) :
savedBuf_(stream.rdbuf()), stream_(stream)
{
stream_.rdbuf(newBuf);
}
~StreamRedirector() {
stream_.rdbuf(savedBuf_);
}
private:
std::streambuf* savedBuf_;
std::ios& stream_;
};
可以这样使用:
using namespace std;
cout << "Hello stdout" << endl;
{
ofstream logFile("log.txt");
StreamRedirector redirect(cout, logFile.rdbuf());
cout << "In log file" << endl;
}
cout << "Back to stdout" << endl;