这篇文章也谈不上原创,只是总结了C/C++文件重定向的几种方式:
注意:转载地址:
源地址:http://blog.csdn.net/chinabinlang/article/details/6408575
www.cnblogs.com/submarinex/
方法一:
#include <stdio.h>
#include <stdlib.h>
FILE *stream;
void main( void )
{
stream = freopen( "freopen.out", "w", stderr );
if( stream == NULL )
fprintf( stdout, "error on freopen/n" );
else
{
fprintf( stream, "This will go to the file 'freopen.out'/n" );
fprintf( stdout, "successfully reassigned/n" );
fclose( stream );
}
system( "type freopen.out" );
}
方法二:
#include <iostream>
#include <fstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ofstream log("foo.txt");
streambuf * oldbuf = cout.rdbuf(log.rdbuf());
cout << "重定向的内容/n" ;
return 0;
}
另外一个示例:
#include <iostream>
#include <fstream>
using namespace std;
void Redirect(ostream &);
int main()
{
cout << "the first row" << endl;
Redirect(cout);
cout << "the last row" << endl;
return 0;
}
void Redirect(ostream &strm)
{
ofstream file("redirect.txt");
// save output buffer of the stream
streambuf *strm_buffer = strm.rdbuf();
// redirect output into the file
strm.rdbuf(file.rdbuf());
file << "one row for the file" << endl;
strm << "one row for the stream" << endl;
// restore old output buffer
strm.rdbuf(strm_buffer);
} // closes file AND its buffer automatically
值得注意的是,在 void Redirect(ostream &) 中的 file 是局部对象,在函数结束时被销毁,相应的 stream 缓冲区也一并被销毁。这和标准的 streams 不同,因为通常 file streams 在构造过程分配 stream 缓冲区,并于析构时销毁它们。所以以上例子中的 cout 不能在被用于写入。事实上它甚至无法在程序结束时被安全销毁。因此我们应该保留旧缓冲区并于事后恢复。
——EOF——
方法三:
freopen("r.txt", "r", stdin );
freopen("r.txt", "w", stdout);
freopen("r.txt", "w", stderr);
方法四:
控制台重定向:常用于MFC于控制台的结合:
AllocConsole();
freopen("CON", "w", stdout );