redirecting cout into file c++

不打扰是莪最后的温柔 提交于 2019-11-29 16:34:51

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!