1. 程式人生 > >C/C++_檔案重定向的幾種方式

C/C++_檔案重定向的幾種方式

這篇文章也談不上原創,只是總結了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 );