redirecting cout into file c++

2019-01-28 15:36发布

问题:

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 achieved by now is that only one cout is saved in the file. I don't want to create separate .txt for each cout, for the sake of reading them at once. My code looks now like this:

#include <fstream>
#include <string>
#include <iostream>

int main()
{
    std::ofstream out("out.txt");
    std::cout.rdbuf(out.rdbuf()); 

    std::cout << "get it3";
    std::cout << "get it4"; 
}

Both cout are in one file, but assuming they are in two different, how to redirect and save in one .txt?

回答1:

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.



标签: c++ cout output