首頁  >  文章  >  後端開發  >  freopen函數的用法詳解

freopen函數的用法詳解

hzc
hzc原創
2020-06-18 16:41:5710656瀏覽

freopen函數的用法詳解

freopen 函数说明

函数名: freopen 
功  能: 实现数据重定向到文件中 
用  法: FILE *freopen(const char *filename, const char *mode, FILE *stream); 
返回值: 成功,则返回文件指针;失败,返回NULL(可以不使用它的返回值) 7 
#include <stdio.h> 

int main(void) 
{ 
   /* redirect standard output to a file */ 
   if (freopen("OUTPUT.FIL", "w", stdout) 
       == NULL) {
      fprintf(stderr, "error redirecting\ 
              stdout\n"); 
  }
   /* this output will go to a file */ 
   printf("This will go into a file."); 

   /* close the standard output stream */ 
   fclose(stdout); 

   return 0; 
}

freopen函數透過實作標準I/O重定向功能來存取文件,而fopen函數則透過文件I/O來存取文件。

freopen函數在演算法競賽中常被使用。在演算法競賽中,參賽者的資料一般需要多次輸入,而為避免重複輸入,使用重定向。

freopen函數在偵錯中非常有用:

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時不要忘記刪除與重定向有關的語句。

推薦教學: 《c

以上是freopen函數的用法詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn