c++ 文件操作

读写文件时要包含头文件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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值