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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM