What I want to do
redirect stdout and stderr to one or more files from inside c++
Why I need it
I am using an external, pr
I was inspired by @POW and @James Kanze 's answers and put together a little RAII class for redirecting std::cout
to a file. It is intended to demonstrate the principle.
Code:
#include
#include
#include
// RAII for redirection
class Redirect {
public:
explicit Redirect(const std::string& filenm):
_coutbuf{ std::cout.rdbuf() }, // save original rdbuf
_outf{ filenm }
{
// replace cout's rdbuf with the file's rdbuf
std::cout.rdbuf(_outf.rdbuf());
}
~Redirect() {
// restore cout's rdbuf to the original
std::cout << std::flush;
_outf.close(); ///< not really necessary
std::cout.rdbuf(_coutbuf);
}
private:
std::streambuf* _coutbuf;
std::ofstream _outf;
};
// == MAIN ==
int main(int argc, char* argv[]) {
std::cout << "This message is printed to the screen" << std::endl;
{
// scope for the redirection
Redirect redirect{ "output.txt" };
std::cout << "This message goes to the file" << std::endl;
}
std::cout << "Printing to the screen again" << std::endl;
}
Output:
This message is printed to the screen
Printing to the screen again
Contents of the file "output.txt"
:
This message goes to the file