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的流緩沖區。程序結束時,改回原來的流緩沖區。
#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 閱讀(2050) 評論(0) 編輯 收藏 所屬分類: C/C++