文件与流
文件操作的基本步骤:
打开文件:
- 建立文件流对象
- 流对象与磁盘文件关联
- 指定文件的打开方式
streamclass fileObj(fileName,openMode);
fileObj.open(fileName,openMode);
文件的打开模式:
打开文件方法1:
调用流类带参数的构造函数,建立流对象时连接外部文件
流类 对象名(文件名,方式);
(流类:ifstream、ofstream或fstream)
例如:ifstream infile(“datafile.dat”,ios::in);
ofstream outfile(“d:\newfile.dat”,ios::out);
方法2:
先建立流对象,再调用fstream::open()函数连接外部文件
流类 对象名;
对象名,open(文件名,方式);
例:打开(创建)一个文件newfile.dat,准备写:
ofstream outfile; //建立输出文件流对象
outfile.open("d:\\newfile.dat",ios::out);
例:打开一个已有文件datafile.dat,准备读:
ifstream infile; //建立输入文件流对象
infile.open("datafile.dat",ios::in);
读/写文件:
<<,put(),write()
>>,get(),getline(),read()
关闭文件:
解除流对象与磁盘文件关联
fileObj.close();
检测输入/输出的状态标志
eofbit: 已到达文件尾
通常使用下面任何一个函数来检测相应的输入/输出状态:
bool eof();
// 假如操作已经到达了文件末尾(eofbit被标设),则eof()函数返回true;
bool fail();
//假如failbit标志被标设,则fail()函数返回true;
简单实例:
#include <fstream>
using namespace std;
int main()
{
ofstream SaveFile("cpp-1.txt"); //打开文件
SaveFile<<"Welcome to HUST!"; //写文件
SaveFIle.close(); //关闭文件
return 0;
}
例:将百鸡问题计算结果存入文件
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
int i,j,k;
ofstream ofile; //定义输出文件
ofile.open("d:\\myfile.txt"); //作为输出文件打开
ofile<<"公鸡 母鸡 小鸡"<<endl;
for(i=0;i<=20;i++)
for(j=0;j<=33;j++)
{
k=100-i-j;
if((5*i+3*j+k/3==100)&&(k%3==0))
ofile<<setw(6)<<i<<setw(10)<<j<<setw(10)<<k<<endl;//写入文件
}
ofile.close();
return 0;
}
读出存放百鸡问题计算结果的文件
#include <fstream>
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
char a[28];
ifstream ifile; //定义输入文件
ifile.open("d:\\myfile.txt"); //作为输入文件打开
int i=0,j,k;
while(ifile.get(a[i]))
{ //读标题,不能用>>,它不能读白字符
if(a[i]=='\n') break;
i++;
}
a[i]='\0';
cout<<a<<endl;
while(1)
{
ifile>>i>>j>>k;
if(ifile.eof()!=0) break; //当读到文件结束时,ifile.eof()为真
cout<<setw(6)<<i<<setw(10)<<j<<setw(10)<<k<<endl;
}
ifile.close();//关闭文件
return 0;
}