1. 程式人生 > >使用檔案進行讀取或輸出的兩種方式(重定向版和fopen版)

使用檔案進行讀取或輸出的兩種方式(重定向版和fopen版)

1.重定向版

//利用檔案進行讀取和輸出(重定向版)
//如果想要標準輸入而檔案輸出時,只需將關於檔案輸入的語句註釋掉即可,檔案輸入標準輸出同理
//如果想回到標準輸入輸出時,只需將下一行的本地定義註釋掉即可
#define LOCAL
#include<iostream>
#include<cstdio>
#include<fstream>
using namespace std;
int main()
{
    #ifdef LOCAL
    freopen("input.txt","r",stdin);                 //scanf從檔案中讀取
    freopen("output.txt","w",stdout);               //printf到檔案
    #endif // LOCAL
    int x,n=0,min=100,max=-100,s=0;
    while(scanf("%d",&x)==1)
    {
        s+=x;
        if(min>x) min=x;
        if(max<x) max=x;
        n++;
    }
    printf("%d %d %.3f\n",min,max,(double)s/n);
    return 0;
}

2.fopen版

//使用檔案輸入輸出,但當禁止使用重定向的方式時,採用如下方法
//此時為檔案讀入,標準輸出
#include<iostream>
#include<cstdio>
#include<fstream>
using namespace std;
int main()
{
    FILE *fin,*fout;
    fin=fopen("input.txt","rb");                //檔案讀取
    //fout=fopen("output.txt","wb");                  //輸出到檔案
    //fin=stdin;                                              //把fopen版的程式改成讀寫標準輸入輸出
    fout=stdout;
    int x,n=0,min=100,max=-100,s=0;
    while(fscanf(fin,"%d",&x)==1)                   //scanf變為fscanf
    {
        s+=x;
        if(min>x) min=x;
        if(max<x) max=x;
        n++;
    }
    fprintf(fout,"%d %d %.3f\n",min,max,(double)s/n);           //printf變為fprintf
    fclose(fin);                                                    //關閉兩個檔案
    fclose(fout);
    return 0;
}