逐梦C++之三:文件输入与输出
1.初识文件的输入与输出
C++提供了对磁盘文件进行读写的支持,并使用一个与输入文件相关的变量来代替cin,其实,从这里我们就可以看出来,cin并不是一个函数,那它是什么呢?它只是istream类的一个对象。Cout其实与cin也是相同的道理,它只是ostream的一个对象,有人会问,为什么cin和cout可以接受不同类型的参数(比如int,char等)呢?那是因为它运算符<<进行了重载.
首先,我们对文件进行处理时必须先包含头文件fstream,操作符>>用于从文件中读取数据,同样,操作符>>用于输出信息到文件当中;
2.从例子分析文件的输入与输出
//==================================================
//程序描述:浅谈C++文件输入与输出
//Date:2016年1月14日 by Ye_wolf
//程序描述:
// This program repeatedly reads an income from
//the file income.in until end-of-file. Income under
//6000 greenbacks is taxed at 30 percent, and income
//greater than or equal to 6000greenbacks is taxed at
//60 percent.After reading each income ,the program
//prints the income and tax.
//备注:
//==================================================
//========================【头文件部分】=============================
#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("infile.in");
outfile.open("outfile.out");
//从infile读取文件信息
while(infile>>income){
if(income<cutoff)
tax=rate1*income;
else
tax=rate2*income;
//输出到文件outfile
outfile<<"Income = "<<income
<<"greenbacks\n"
<<"Tax ="<<tax
<<" greenbacks\n";
}
//关闭文件
infile.close();
outfile.close();
return 0;
}
运行结果:
1.Infile.in
2.outfile.out
解析:
1.书写头文件。
头文件必须写进去fstream,因为我们没有用到标准输入与输出,所以就不需要写iostream
2.定义处理文件的相关类型的变量(对象)。
对文件进行处理,我们必须定义相关的变量来做相应的动作;可以这样理解,文件其实就是一串字节流,你若要处理,肯定不能用文件名直接进行相关动作,自然我们就需要定义一个变量来处理;ifstream:读取文件类型;ofstream:写入文件类型;
ifstream infile;
ofstream outfile;
3.打开文件。
定义好了变量后,我们就需要用这个变量来打开文件;
infile.open(“infile.in”);
outfile.open(“outfile.out”);
4.读取数据和写入数据
。我们通过在第二步定义的变量使用操作符>>来读取数据;使用操作符<<来向文件中写入数据;(注意:读取类型的文件变量只能用来读取数据,写入类型的文件变量只能用来写入)
infile>>income;
outfile<<"Income = "<<income
<<"greenbacks\n"
<<"Tax ="<<tax
<<" greenbacks\n";
5.关闭文件。
既然有打开文件,自然我们要关闭文件,做到有始有终。
infile.close();
outfile.close();
3.测试文件打开状态
在我们打开文件时,可能因为各种各样的原因打不开而导致我们的程序不能正常运行,而测试文件打开状态可以让我们迅速找到出错的位置所在。
例子:
ifstream infile;
infile.oppen(“infile.in”);
if(!infile)
{
cerr<<"infile.in文件打开失败!"
exit(0);//注意exit需要头文件cstdlib
}