使用cout或cerr在重定向到文件后输出到控制台 [英] Use cout or cerr to output to console after it has been redirected to file

查看:1050
本文介绍了使用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;

这篇关于使用cout或cerr在重定向到文件后输出到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆