freopen 函數的用法

來源:互聯網
上載者:User

 

這次用到的檔案開啟函數不再是fopen,而是stdio.h中包含的另一個函數freopen

FILE * freopen ( const char * filename, const char * mode, FILE * stream );

【參數說明】

filename: 要開啟的檔案名稱

mode: 檔案開啟的模式,和fopen中的模式(r/w)相同

stream: 檔案指標,通常使用標準流檔案(stdin/stdout/stderr)

【使用方法】

因為檔案指標使用的是標準流檔案,因此我們可以不定義檔案指標。

接下來我們使用freopen()函數以唯讀方式r(read)開啟輸入檔案slyar.in

freopen("slyar.in", "r", stdin);

然後使用freopen()函數以寫入方式w(write)開啟輸出檔案slyar.out

freopen("slyar.out", "w", stdout);

接下來的事情就是使用freopen()函數的優點了,我們不再需要修改scanf和printf,而是維持代碼的原樣就可以了。因為freopen()函數重新導向了標準流,使其指向前面指定的檔案,省時省力啊,贊...

最後只要使用fclose關閉輸入檔案和輸出檔案即可。

fclose(stdin);
fclose(stdout);

若要恢複控制代碼,可以重新開啟標準控制台裝置檔案,只是這個裝置檔案的名字是與作業系統相關的。

DOS/Win:

freopen("CON", "r", stdin);

Linux:

freopen("/dev/console", "r", stdin);

也附加一個代碼模版:

#include <stdio.h>
             
int main()
{
     freopen("slyar.in", "r", stdin);
     freopen("slyar.out", "w", stdout);
             
     /**//* 中間按原樣寫代碼,什麼都不用修改 */
             
     fclose(stdin);
     fclose(stdout);
     return 0;
}

PS.剛才發現一個問題,就是在用C-free編譯含有檔案操作的源碼時,必須要將fopen或者freopen放到所有變數定義的下面,否則會編譯錯誤...囧

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.