我们写程序的时候,为了方便,经常需要修改流的方向,或者将默认的输出流重定向到我们的文件或者是内存中,而不是系统默认的终端。参考代码如下:
#include <iostream>
#include <fstream>
int main(int argc, char* argv[])
{
std::ofstream StreamOut( "out.txt");
std::streambuf * OldBuf = std::cout.rdbuf( streamOut.rdbuf());
//写入out.txt文件中
streamOut << "streamOut\n";
std::cout << "std::cout\n";
//注意恢复
std::cout.rdbuf( OldBuf);
return 0;
}
下面是如何使得上面的代码自动运行:
#include <iostream>
template< class char_type, class char_traits = std::char_traits< char_type> >
class basic_redirect_from_to
{
typedef std::basic_ios< char_type, char_traits> ios_type;
typedef std::basic_streambuf< char_type, char_traits> streambuf_type;
typedef basic_redirect_from_to< char_type, char_traits> this_class;
basic_redirect_from_to( const this_class & );
this_class & operator=( this_class &);
public:
basic_redirect_from_to( ios_type & streamFrom, ios_type & streamTo)
: m_streamFrom( streamFrom)
{
m_pOriginalBuffer = m_streamFrom.rdbuf( streamTo.rdbuf());
}
~basic_redirect_from_to()
{
m_streamFrom.rdbuf( m_pOriginalBuffer);
}
private:
ios_type & m_streamFrom;
streambuf_type * m_pOriginalBuffer;
};
typedef basic_redirect_from_to< char> redirect_from_to;
typedef basic_redirect_from_to< wchar_t> wredirect_from_to;