天天看點

freopen-C/C++友善的檔案輸入輸出

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

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

下面為兩個a+b測試程式

C文法

#include<stdio.h>
int main()
{
  freopen("input.txt", "r", stdin);
  freopen("out.txt","w",stdout);
  int a, b;
  scanf("%d %d",&a,&b);
  printf("%d\n",a+b);
  fclose(stdin);
  fclose(stdout);
  return 0;
}
           

C++文法

#include<iostream>
#include<stdio.h>
using namespace std;

int main()
{
  freopen("input.txt", "r", stdin);
  freopen("out.txt","w",stdout);
  int a, b;
  cin>>a>>b;
  cout<<a+b;
  return 0;
}
           

 freopen("input.txt","r",stdin)的作用就是把标準輸入流stdin重定向到 input.txt檔案中,這 樣在用scanf或是用cin輸入時便不會從标準輸入流讀取資料,而是從input.txt檔案中擷取輸入。隻要把輸入資料事先粘貼到input.txt,調試時就方 便多了。 

類似的,freopen("out.txt","w",stdout)的作用就是把stdout重定向到out.txt檔案中,這樣輸出結果需要打開out.txt檔案檢視。