c + +复制标准输出通过重定向COUT到文件 [英] C++ duplicate stdout to file by redirecting cout

查看:353
本文介绍了c + +复制标准输出通过重定向COUT到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天。

我必须使用产生大量的调试信息到标准输出的一些外部功能(通过的std :: COUT )。我想通过重定向 COUT 提振 tee_device 复制此信息的一些日志文件。我用下面的例子code:

I have to use some external functions that produce a lot of debugging information to stdout (via std::cout). I want to duplicate this information to some log file by redirecting cout to boost tee_device. I use the following example code:

typedef boost::iostreams::tee_device<ostream, ofstream> TeeDevice;
typedef boost::iostreams::stream<TeeDevice> TeeStream;

int main(int argc, char** argv) {

    remove("file.log");
    ofstream logFile;
    logFile.open("file.log");
    TeeDevice outputDevice(cout, logFile);
    TeeStream logger(outputDevice);    

    cout.rdbuf(logger.rdbuf());
    cout << "some log info";//this should print both to stdout and to file

    logger.close();
}

不过,我试图运行这个时候有一个分段错误。为什么?

However I have a segmentation fault when trying to run this. Why?

我知道我能做到像

    logger << "some debug log info";

但我需要确切地重定向 COUT 。我怎样才能获得呢?

谢谢,
斯坦尼斯

Thanks, Stanislav

推荐答案

您设置 TeeDevice 输出到的std :: COUT ,然后用它替换的 rdbuf 一个依赖于 TeeDevice (取决于性病::法院)。

You set TeeDevice output to std::cout, and then substitute it's rdbuf with one which depends on TeeDevice (which depends on std::cout).

问题是由通过临时的std :: ostream的持有指向原始的 rdbuf 打破这一循环解决的std :: COUT

Problem is solved by breaking that cycle via temporary std::ostream which holds pointer to original rdbuf of std::cout:

int main()
{
    remove("file.log");
    ofstream logFile;
    logFile.open("file.log");

    ostream tmp(cout.rdbuf()); // <----
    TeeDevice outputDevice(tmp, logFile); // <----
    TeeStream logger(outputDevice);    

    cout.rdbuf(logger.rdbuf());
    cout << "some log info" << endl;

    logger.close();
}

上Coliru 在线演示

这篇关于c + +复制标准输出通过重定向COUT到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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