输出重定向在命令行中,可以用 > 和 >> 等实现。但是有时候我们希望通过编程来实现,以下是一个最简单的 C++ 版本。
#include <ios>
#include <iostream>
#include <fstream>

int main( )
{
using namespace std;
ofstream file( "rdbuf.txt" );
streambuf *x = cout.rdbuf( file.rdbuf( ) );
cout << "test" << endl; // Goes to file
cout.rdbuf(x);
cout << "test2" << endl;

return 0;
}
by qyang















by qyang