读写文件时要包含头文件fstream;
例:读取income.in的数字计算后输出到tax.out中
#include<fstream>
using namespace std;
const int cutoff = 6000;
const float rate1 = 0.3;
const float rate2 = 0.6;
int main(){
ifstream infile;
ofstream outfile;
int income, tax;
infile.open( "income.in.txt");
outfile.open("tax.out.txt");
while( infile >> income ){
if(income < cutoff) tax = rate1 * income;
else tax = rate2 * income;
outfile << "Income = " << income
<< " greenbacks\n"
<< "Tax = " << tax
<< " greenbacks\n";
}
infile.close();
outfile.close();
return 0;
}
测试文件是否打开:
若ifstream infile; infile.open("xxx.txt");
执行后,if(infile)
中表达式为真;
例:打开scores.dat,如果打开文件失败,则提示用户并终止程序
#include<fstream>
#include<cstdlib>
#include<iostream>
using namespace std;
int main(){
ifstream infile;
infile.open("scores.dat");
if(!infile){
cerr << "unable to open scores.dat\n";
exit(0);
}
return 0;
}
例2:从yard.in中读入一个数,将这个数加一后输出到length.out中。若无法打开则提示信息
#include<fstream>
#include<cstdlib>
#include<iostream>
using namespace std;
int main(){
ifstream infile;
ofstream outfile;
int yard, length;
infile.open("yard.in.txt");
outfile.open("length.out.txt");
if(!infile){
cerr << "unable to open yard.in";
exit(0);
}
while(infile >> yard){
length = yard+1;
outfile << length << '\n';
}
infile.close();
outfile.close();
return 0;
}