Replacing Stream Buffers

Answer To: http://forum.codecall.net/c-c/25478-standard-output-monitor.html

#include <iostream>
#include <exception>
#include <fstream>
 
int main(const int argc, const char *argv[]) {
    std::fstream    _logfile;
    std::streambuf  *_old_cout_buffer;
 
    // You need to pass a filename to write to
    if (argc < 2) {
        std::cout << "Usage: " << argv[0] << " <filename>" << std::endl;
        return 0;
    }
 
    // Attempt to open the file, in output (fstream::out) mode, appending (std::fstream::app) text.
    try {
        _logfile.open(argv[1],std::fstream::out | std::fstream::app);
        // Make sure the file is open
        if (_logfile.is_open()) {
            // Backup the old stream buffer so we can restore it later
            _old_cout_buffer = std::cout.rdbuf();
            // Change std::cout's buffer to the file
            std::cout.rdbuf(_logfile.rdbuf());
        }
    }
    // Something went wrong, and we couldn't open the file.
    catch (std::fstream::failure &e) {
        std::cout << "Couldn't open " << argv[1] << " for output!" << std::endl;
        return 1;
    }
 
    // If everything went well, this'll be written into the file you passed on the command line.
    std::cout << "Hello World :D" << std::endl;
 
    // And restoring the buffer
    std::cout.rdbuf(_old_cout_buffer);
 
    return 0;
}
 
cpp/replacing_stream_buffers.txt · Last modified: 2010/02/12 21:36 by TkTech
 
Except where otherwise noted, content on this wiki is licensed under the following license:Public Domain
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki