Output redirection

May 2, 2012 at 2:56pm
Alright. I know how to redirect cout, cerr, clog, and I'd expect ofstream objects, with the rdbuf() and open() methods. But is there any way to redirect any of these back to the command line after directing all of them to files? Anther similar, perhaps clearer, phrasing: say cout, cerr, and clog are all redirected to files. Is there any way to redirect them back to the command line?
Last edited on May 2, 2012 at 3:16pm
May 2, 2012 at 3:17pm
1
2
3
4
5
6
7
8
9
std::cout << "to stdout" << std::endl ;

std::filebuf buf ;
buf.open( "output_file_name", std::ios::out ) ; ;
auto oldbuf = std::cout.rdbuf( &buf ) ;
std::cout << "to file" << std::endl ;

std::cout.rdbuf( oldbuf ) ;
std::cout << "back to stdout" << std::endl ;

May 2, 2012 at 3:38pm
I'm sorry, but I'm not sure I completely understand how that works. What sort of #include headers do I need, and how exactly does it work?

Ah, yes, my IDE's getting mad at me cos auto is a C++11 extension.
Last edited on May 2, 2012 at 3:40pm
May 2, 2012 at 3:44pm
> What sort of #include headers do I need
<iostream> and <fstream>

> I'm sorry, but I'm not sure I completely understand how that works.

Save a pointer to the old std::streambuf associated with std::cout, and restore the buffer when we want the output to be back to stdout.

> my IDE is getting mad at me cos I don't have C++11

Nothing specific to C++11 except type inference with auto. Equivalent C++98:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <fstream>

int main()
{
    std::cout << "to stdout" << std::endl ;
    std::filebuf buf ;

    buf.open( "output_file_name", std::ios::out ) ; ;
    std::streambuf* oldbuf = std::cout.rdbuf( &buf ) ;
    std::cout << "to file" << std::endl ;

    std::cout.rdbuf( oldbuf ) ;
    std::cout << "back to stdout" << std::endl ;
}

May 2, 2012 at 4:05pm
Thanks loads!
Topic archived. No new replies allowed.