Use cout or cerr to output to console after it has been redirected to file

折月煮酒 提交于 2019-12-24 01:47:10

问题


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?


回答1:


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

Can be used like this:

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;



回答2:


You save the buffer and restore it later:

std::streambuf *buf = std::cout.rdbuf(); //save
// Do other stuff
std::cout.rdbuf(buf); // restore


来源:https://stackoverflow.com/questions/14287777/use-cout-or-cerr-to-output-to-console-after-it-has-been-redirected-to-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!