1. 程式人生 > >比賽中控制從檔案輸入輸出,freopen或fopen版

比賽中控制從檔案輸入輸出,freopen或fopen版

比賽或者練習中,輸入重複內容進行debug讓人頭疼,因此,平時練習,可以在檔案裡輸入輸出,避免命令列的繁瑣。

  • freopen版,從input.txt輸入,printf會列印到檔案output.txt中。
#include<stdio.h>
int main()
{
	/*重定向版輸入輸出只要加入這兩句話即可 
	freopen("D:\\程式碼\\input.txt","r",stdin);
	freopen("D:\\程式碼\\output.txt","w",stdout);

        在不需要從檔案輸入輸出後,可以轉換到控制檯輸入輸出:
        freopen("CON","r",stdin);
        freopen("CON","w",stdout);
	*/
	
	int x,min,max,s=0;
	double n=0;
	scanf("%d",&x);
	min=max=x;
	n++;
	s+=x;
	
	while(scanf("%d",&x)==1)
	{
		s+=x;
		if(x>max)max=x;
		if(x<min)min=x;
		n++;
	}
	printf("%d %d %.3lf",min,max,double(s/n));
	
	return 0;
} 
  • fopen版,

注意

1.要定義FILE 型別的指標,它們各自指向要讀取和寫入的檔案。

2.要用fscanf,fprintf函式。

3.關閉檔案,節省資源。

#include<stdio.h>
int main()
{
	/*重定向版輸入輸出只要加入這兩句話即可 
	freopen("D:\\程式碼\\input.txt","r",stdin);
	freopen("D:\\程式碼\\output.txt","w",stdout);
	*/
	
	FILE *fin,*fout;
	fin=fopen("D:\\程式碼\\input.txt","rb");
	fout=fopen("D:\\程式碼\\output.txt","wb"); 
	int x,min,max,s=0;
	double n=0;
	fscanf(fin,"%d",&x);
	min=max=x;
	n++;
	s+=x;
	
	while(fscanf(fin,"%d",&x)==1)
	{
		s+=x;
		if(x>max)max=x;
		if(x<min)min=x;
		n++;
	}
	fprintf(fout,"%d %d %.3lf",min,max,double(s/n));
	fclose(fin);
	fclose(fout);
	
	return 0;
}