In my development, I want to use the DUAN written program, I directly put the code of the code to my program.
The output of Duan's program is that the direct output to the standard output is also on the screen, and the output of my program is in the log file. If I go directly to change his code, it will bring a lot of trouble. In this case, the easiest way is to redirect the standard output stream into the file.
I use the method of replacing the stream buffer to redirect streams, with the RDBuf function to replace the COUT buffer with the RDBUF function, so that the data sent to the COUT buffer will be sent to this file, wait until the end of the program , Change back to the original stream buffer.
#include
#include
int main ()
{
Std :: OFSTREAM log ("foo.log");
Std :: streambuf * Oldbuf = std :: cout.rdbuf (log.rdbuf ());
Std :: cout << "Output to standard output, but actually outputs in the foo.log file / n";
LOG << "Outputs to the file, although the COUT is redirected to the log, but does not affect the use of the log itself / N";
// Restore stream buffer
Std :: Cout.rdbuf (Oldbuf);
}
note:
1. COUT can call RDBUF to replace buffers, but log cannot replace the buffer by calling RDBUF. Because of the same functionality because of the RDBUF of Ofstream.
2. Convection redirection, just in one code block {}, this {} is restored to the original, but the function of the function called in this code block will also take effect.