c++的streaming

来源:互联网 发布:数据泄露调查报告 编辑:程序博客网 时间:2024/04/28 21:53
#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管理的流缓冲区的指针。重载版本允许你替换流缓
冲区,返回值是原始的流缓冲区。
原创粉丝点击