my problem is I have a couple of cout\'s in various files in the project. I would like all of them to be redirected and saved in .txt file, and what I achie
The obvious answer is that you should never output to
std::cout
. All actual output should be to an std::ostream&
,
which may be set to std::cout
by default, but which you can
initialize to other things as well.
Another obvious answer is that redirection should be done before starting the process.
Supposing, however, that you cannot change the code outputting
to std::cout
, and that you cannot control the invocation of
your program (or you only want to change some of the outputs),
you can change the output of std::cout
itself by attaching
a different streambuf
. In this case, I'd use RAII as well, to
ensure that when you exit, std::cout
has the streambuf it
expects. But something like the following should work:
class TemporaryFilebuf : public std::filebuf
{
std::ostream& myStream;
std::streambuf* mySavedStreambuf;
public:
TemporaryFilebuf(
std::ostream& toBeChanged,
std::string const& filename )
: std::filebuf( filename.c_str(), std::ios_base::out )
, myStream( toBeChanged )
, mySavedStreambuf( toBeChanged.rdbuf() )
{
toBeChanged.rdbuf( this );
}
~TemporaryFilebuf()
{
myStream.rdbuf( mySavedStreambuf );
}
};
(You'll probably want to add some error handling; e.g. if you cannot open the file.)
When you enter the zone where you wish to redirect output, just
create an instance with the stream (std::cout
, or any other
ostream
) and the name of the file. When the instance is
destructed, the output stream will resume outputting to
whereever it was outputting before.