#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函數(shù)返回一個由基類basic_ios管理的流緩沖區(qū)的指針。重載版本允許你替換流緩沖區(qū),返回值是原始的流緩沖區(qū)。解決方法很簡單—用你的log文件的流緩沖區(qū)替換cout和cerr的流緩沖區(qū)。程序結(jié)束時,改回原來的流緩沖區(qū)。