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

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

}

你可能感兴趣的:(C++,File,include,Go,iostream,output)