///////////////////////////////////////////////////////////////////// // reDirect.cpp - redirect cout to a log file using streambufs // // // // Jim Fawcett, CSE687 - OOD, Spring 2001 // ///////////////////////////////////////////////////////////////////// #include #include using namespace std; void main() { cout << "\n Demonstrate Redirecting cout to a Log File " << "\n ============================================\n"; cout << "\n This output text will be displayed on cout, " << "\n then redirected to a log file using streambufs." << "\n Note that all output is written to cout." << "\n Redirection occurs by giving cout the streambuf" << "\n of the log file\n\n"; cout << "\n Look in LogFile.txt to see the output\n\n"; ofstream out("LogFile.txt"); if(out) { streambuf *pStreambuf = cout.rdbuf(); // save cout streambuf cout.rdbuf(out.rdbuf()); // give cout file's streambuf // The following text will be written to LogFile.txt. You might // want to do something like this to give a user the option of // seeing output on-screen, or getting it off-line in a file. cout << "\n This output text will be displayed on cout, " << "\n then redirected to a log file using streambufs." << "\n Note that all output is written to cout." << "\n Redirection occurs by giving cout the streambuf" << "\n of the log file\n\n"; cout.rdbuf(pStreambuf); // restore cout streambuf out.close(); } }