改变流的方向可以使用stream的.rdbuf()成员函数。.rdbuf()函数允许你得到以及设置底层流缓冲。如果你重新设置std::cout的底层流缓冲指向一个文件流缓冲,那么你就改变了它的方向。
#include <iostream>
#include <fstream>
int main(int argc, char* argv[])
{
std::ofstream streamOut( "out.txt");
std::streambuf * pOldBuf = std::cout.rdbuf( streamOut.rdbuf());
//下面这两行都写道out.txt文件中去
streamOut << "using streamOut
";
std::cout << "using std::cout
";
//防止内存泄漏和其它问题
std::cout.rdbuf( pOldBuf);
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;
#include <fstream>
int main(int argc, char* argv[])
{
std::ofstream streamOut( "out.txt");
redirect_from_to r( std::cout, streamOut);
redirect_from_to r2( std::cerr, streamOut);
streamOut << "using streamOut.
"
<< std::endl ;
std::cout << "using std::cout
"<<
std::endl ;
std::cerr << "using std::cerr
"<<
std::endl ;
return 0;
}