freopen,,fopen,ifstream/ofstream
1. 开始的时候freopen很直观,特别是改熟悉的键盘输入in(屏幕监控)和屏幕输出out,再直接。
xInOut01.cpp
# include<cstdio>
int main( ){freopen("in.txt", "r", stdin);freopen("out.txt", "w", stdout); int temp,sum= 0;while (scanf("%d", &temp)==1) {sum=sum+temp;} printf("%d\n",sum);fclose(stdin);fclose(stdout); return 0;
}
可以再简单点,用cin/cout
xInOut02.cpp
#include<cstdio>
#include<iostream>using namespace std;
int main( ){freopen("in.txt", "r", stdin);freopen("out.txt", "w", stdout); int temp,sum= 0;while(cin>>temp){sum=sum+temp;}cout<<sum<<endl;fclose(stdin);fclose(stdout); return 0;
}
实际这个redirect重定向,就是用standIn键盘和standOut屏幕,注释的五行可以明确.
xInOut03.cpp
#include<iostream>
using namespace std;
int main()
{
// FILE *fin, *fout;
// fin=fopen("in.txt","rb");
// fout=fopen("out.txt"," wb");int a,b,c;cin>>a>>b>>c;cout<<(a+b)/c<<endl;// fclose(stdin);
// fclose(stdout); return 0;
}
FILE *freopen(const char *filename, const char *mode, FILE *stream)
mode(6): r, w, a, r+, w+, a+
stream(5): stdin, stdout, stderr
用fopen是规矩,毕竟不再是初学的键盘屏幕。
FILE *fopen(const char *filename, const char *mode)
mode同前.。
xInOut04.cpp
#include<cstdio>
using namespace std;int main( ){FILE *fin, *fout;fin=fopen("in.txt","rb"); //rb可以fout=fopen("out.txt"," wb"); //wb可以int temp, sum=0;while(fscanf(fin,"%d", &temp)==1)sum=sum+temp;fprintf(fout,"%d\n", sum);fclose(fin);fclose(fout);return 0;
}
怀念freopen,用FILE指针,把输入输出定向到文件。其中看不出fopen, 但对应的fclose还是用一下。
xInOut05.cpp
#include<cstdio>
#include<iostream>
using namespace std;int main( ){FILE *fin, *fout;fin=stdin;fout=stdout;freopen("in.txt", "r", stdin);freopen("out.txt", "w", stdout);int temp, sum=0;while(fscanf(fin,"%d", &temp)==1)sum=sum+temp;fprintf(fout,"%d\n", sum);fclose(stdin);fclose(stdout); return 0;
}
用ifstream/ofstream/fstream(实际是三个)
*xInOut06.cpp
# include<fstream>
using namespace std;
int main( ){ifstream fin("in.txt");ofstream fout("out.txt");int temp, sum =0;while (fin>>temp)sum=sum+temp;fout<<sum<<endl;fin.close();fout.close();return 0;
}
这里直接是构造函数,实际实例化后该用open,close操作。
void open(const char *filename, ios::openmode mode);
mode(5):ios::app(append添加), ios::ate(a FILE to end找尾), ios::in(reading in读入), ios::out(writing out写出), ios::trunc(truncated清干净)---参数可结合如(ios::out|ios:trunc 清干净准备写)。
实际代码还想换成初期,把上面的注释并用define,可以又回到cin/cout的模样:
xInOut07.cpp
#include<fstream>
#include<iostream>
#define fin cin
#define fout coutusing namespace std;
int main( ){//ifstream fin("in.txt");//ofstream fout("out.txt");int temp, sum =0;while (fin>>temp)sum=sum+temp;fout<<sum<<endl;//fin.close();//fout.close();return 0;
}
最后in.txt和out.txt文件如下
**********************************in.txt***********************
1 2 3 4 5
*****************************************************************
******************************out.txt****************************
15
***************************************************************