redirecting cout into file c++

前端 未结 1 2045
半阙折子戏
半阙折子戏 2020-12-21 14:37

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

相关标签:
1条回答
  • 2020-12-21 14:55

    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.

    0 讨论(0)
提交回复
热议问题