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

來源:互聯網
上載者:User

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

#include <stdio.h> // 實際使用中發現freopen也包含在iostream.h中,C++代碼#include <iostream.h>即可。             int main(){     freopen("sample.in", "r", stdin);     freopen("sample.out", "w", stdout);                  /* 同控制台輸入輸出 */                  fclose(stdin);     fclose(stdout);     return 0;}

-----轉自: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時不要忘記把與重新導向有關的語句刪除。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.