1. 程式人生 > >freopen - C/C++檔案輸入輸出利器

freopen - C/C++檔案輸入輸出利器

freopen以前經常使用,比較方便,可以當作模板,在中間替換為自己的程式碼即可使用。

[cpp] view plain copy
  1. #include <stdio.h> //C++程式碼#include <iostream.h>即可。  
  2.                
  3. int main()  
  4. {  
  5.      freopen("sample.in""r", stdin);  
  6.      freopen("sample.out""w", stdout);  
  7.                
  8.      /* 同控制檯輸入輸出 */  
  9.                
  10.      fclose(stdin);  
  11.      fclose(stdout);  
  12.   
  13.      return 0;  
  14. }  

-----轉自:http://www.slyar.com/blog/c-freopen-stdin-stdout.html -------------

當我們求解acm題目時,通常在設計好演算法和程式後,要在除錯環境(例如VC等)中執行程式,輸入測試資料,當能得到正確執行結果後,才將程式提交到oj中。但由於除錯往往不能一次成功,每次執行時,都要重新輸入一遍測試資料,對於有大量輸入資料的題目,輸入資料需要花費大量時間。

        使用freopen函式可以解決測試資料輸入問題,避免重複輸入,不失為一種簡單而有效的解決方法。 

 函式名: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是標準錯誤流,一般把螢幕設為預設。


        下面以在VC下除錯“計算a+b”的程式舉例。
C語法:
#include <stdio.h>
int main()
{
int a,b;
freopen("debug\\in.txt","r",stdin); //輸入重定向,輸入資料將從in.txt檔案中讀取
freopen("debug\\out.txt","w",stdout); //輸出重定向,輸出資料將儲存在out.txt檔案中
while(scanf("%d %d",&a,&b)!=EOF)
printf("%d\n",a+b);
fclose(stdin);//關閉檔案
fclose(stdout);//關閉檔案
return 0;
}

C++語法
#include <stdio.h>
#include <iostream.h>
int main()
{
int a,b;
freopen("debug\\in.txt","r",stdin); //輸入重定向,輸入資料將從in.txt檔案中讀取
freopen("debug\\out.txt","w",stdout); //輸出重定向,輸出資料將儲存在out.txt檔案中
while(cin>>a>>b)
cout<<a+b<<endl; // 注意使用endl
fclose(stdin);//關閉檔案
fclose(stdout);//關閉檔案
return 0;
}
        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檔案檢視。

        需要說明的是:
        1. 在freopen("debug\\in.txt","r",stdin)中,將輸入檔案in.txt放在資料夾debug中,資料夾debug是在VC中建立工程檔案時自動生成的除錯資料夾。如果改成freopen("in.txt","r",stdin),則in.txt檔案將放在所建立的工程資料夾下。in.txt檔案也可以放在其他的資料夾下,所在路徑寫正確即可。
        2. 可以不使用輸出重定向,仍然在控制檯檢視輸出。
        3. 程式除錯成功後,提交到oj時不要忘記把與重定向有關的語句刪除。




FROM:  http://www.cnblogs.com/pegasus923/archive/2011/04/22/2024418.html