I have a program in c++, during the program i use :
static ofstream s_outF(file.c_str());
if (!s_outF)
{
cerr << "ERROR : could not open file " << file << endl;
exit(EXIT_FAILURE);
}
cout.rdbuf(s_outF.rdbuf());
Meaning i redirect my cout to a file. What would be the easiest way to return the cout back to the standard output?
thanks.
Save the old streambuf before you change cout's streambuf :
auto oldbuf = cout.rdbuf(); //save old streambuf
cout.rdbuf(s_outF.rdbuf()); //modify streambuf
cout << "Hello File"; //goes to the file!
cout.rdbuf(oldbuf); //restore old streambuf
cout << "Hello Stdout"; //goes to the stdout!
You can write a restorer to do that automatically as:
class restorer
{
std::ostream & dst;
std::ostream & src;
std::streambuf * oldbuf;
//disable copy
restorer(restorer const&);
restorer& operator=(restorer const&);
public:
restorer(std::ostream &dst,std::ostream &src): dst(dst),src(src)
{
oldbuf = dst.rdbuf(); //save
dst.rdbuf(src.rdbuf()); //modify
}
~restorer()
{
dst.rdbuf(oldbuf); //restore
}
};
Now use it based on scope as:
cout << "Hello Stdout"; //goes to the stdout!
if ( condition )
{
restorer modify(cout, s_out);
cout << "Hello File"; //goes to the file!
}
cout << "Hello Stdout"; //goes to the stdout!
The last cout would output to stdout even if condition is true and the if block is executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With