这篇文章也谈不上原创,只是总结了C/C++文件重定向的几种方式:
注意:转载说明出处 chinabinlang 的CSDN ;
方法一:
#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;
}
方法三:
freopen("r.txt", "r", stdin );
freopen("r.txt", "w", stdout);
freopen("r.txt", "w", stderr);
方法四:
控制台重定向:常用于MFC于控制台的结合:
AllocConsole();
freopen("CON", "w", stdout );