文件輸入輸出(一):重定向

函數名:freopen 
聲明:FILE *freopen( const char *path, const char *mode, FILE *stream ); 
所在文件: stdio.h 
參數說明: 
path: 文件名,用於存儲輸入輸出的自定義文件名。 
mode: 文件打開的模式。和fopen中的模式(如r-只讀, w-寫)相同。 
stream: 一個文件,一般使用標準流文件。 
返回值:成功,則返回一個path所指定文件的指針;失敗,返回NULL。(通常能夠不使用它的返回值) 
功能:實現重定向,把預約義的標準流文件定向到由path指定的文件中。標準流文件具體是指stdin、stdout和stderr。其中stdin是標準輸入流,默認爲鍵盤;stdout是標準輸出流,默認爲屏幕;stderr是標準錯誤流,通常把屏幕設爲默認。
 freopen("debug\\in.txt","r",stdin)的做用就是把標準輸入流stdin重定向到debug\\in.txt文件中,這樣在用scanf或是用cin輸入時便不會從標準輸入流讀取數據,而是從in.txt文件中獲取輸入。只要把輸入數據事先粘貼到in.txt,調試時就方便多了。 
相似的,freopen("debug\\out.txt","w",stdout)的做用就是把stdout重定向到debug\\out.txt文件中,這樣輸出結果須要打開out.txt文件查看。 
 須要說明的是:
    在freopen("debug\\in.txt","r",stdin)中,將輸入文件in.txt放在文件夾debug中,文件夾debug是在VC中創建工程文件時自動生成的調試文件夾。若是改爲freopen("in.txt","r",stdin),則in.txt文件將放在所創建的工程文件夾下。in.txt文件也能夠放在其餘的文件夾下,所在路徑寫正確便可。
以下代碼爲從文件從獲取變量並將二者的和輸入另外一個文件:

#include <iostream>
#include<cstdio>
using namespace std;
int main()
{
  freopen("input.txt","r",stdin);
  freopen("output.txt","w",stdout);
  int a,b;
  while(cin>>a>>b){
  cout<<a+b<<endl;
  }
  fclose(stdin);
  fclose(stdout);
  return 0;
}ios

相關文章
相關標籤/搜索