weidagang2046的专栏

物格而后知致
随笔 - 8, 文章 - 409, 评论 - 101, 引用 - 0
数据加载中……

C++标准I/O重定向

#include <iostream>
#include <fstream>
int main()
{
    std::ofstream logFile("out.txt");
    std::streambuf *outbuf = std::cout.rdbuf(logFile.rdbuf());
    std::streambuf *errbuf = std::cerr.rdbuf(logFile.rdbuf());

    // do the actual work of the program;
    // GUI code and event loop would go here
    std::cout << "This would normally go to cout but goes to the log file\n";
    std::cerr << "This would normally go to cerr but goes to the log file \n";
    logFile << "This goes to the log file\n";
    // end of program body

    // restore the buffers
    std::cout.rdbuf(outbuf);
    std::cerr.rdbuf(errbuf);
}

rdbuf函数返回一个由基类basic_ios管理的流缓冲区的指针。重载版本允许你替换流缓冲区,返回值是原始的流缓冲区。解决方法很简单—用你的log文件的流缓冲区替换cout和cerr的流缓冲区。程序结束时,改回原来的流缓冲区。

posted on 2006-11-19 21:38 weidagang2046 阅读(2018) 评论(0)  编辑  收藏 所属分类: C/C++


只有注册用户登录后才能发表评论。


网站导航: