且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用cout或cerr在重定向到文件后输出到控制台

更新时间:2023-12-05 12:59:28

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;