关闭

C++中关于输出流重定向到文件

2025人阅读 评论(1) 收藏 举报

#include <iostream>

#include <fstream>

void main()

{

    std::ofstream logFile("c://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);

 

              // It will output in your console

              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";

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:330554次
    • 积分:5824
    • 等级:
    • 排名:第4396名
    • 原创:248篇
    • 转载:19篇
    • 译文:0篇
    • 评论:38条
    最新评论