Bobface
Bobface

Reputation: 2952

Detour cout to custom function

I have made a pretty big program which prints very much information to the screen all the time. The thing is that I can't be there all the time to read and eventually spot errors. So I came up with the idea to write everything that is printed by cout to a file. The problem is that, how I already wrote, there are plenty "cout's". Working through the whole code and replacing every cout by a custom function would be very annoying.

Is there a way I how I can "hook" cout to be redirected to a custom function of mine?

Upvotes: 1

Views: 661

Answers (2)

P0W
P0W

Reputation: 47814

You can redirect standard output directly to to file using command line with output redirection

fileneame.exe > log.txt
     or
./filename > log.txt

Else use some RAII, something like following:

class Logger
{
    std::ofstream filehandle;
    std::ostream&   myStream;
    std::streambuf* mySavedStreambuf;

public:
    Logger( std::ostream& oldStream, std::string const& filename)
        : filehandle(filename)
        , myStream(oldStream)
        , mySavedStreambuf(oldStream.rdbuf())
    {
        oldStream.rdbuf(filehandle.rdbuf());
    }
    ~Logger()
    {
        myStream.rdbuf(mySavedStreambuf);
    }
};

And then in your intilization/main routine do something like:

int main()
{

 {
      Logger temp( std::cout, "log.txt" );
      // call funcs that has std::cout, all outputs will be in log.txt
 }// temp goes out of scope, std::cout restored.

 // Call funcs that has std::cout, now all outputs on standard ouput.

}

Upvotes: 2

vitaut
vitaut

Reputation: 55594

You can provide a custom stream buffer via the rdbuf method. Here's an example that redirects cout to a file:

std::ofstream ofs("output");
std::cout.rdbuf(ofs.rdbuf());

Upvotes: 3

Related Questions