输出文件流:从内存流向外存的数据
输入文件流:从外存流入内存的数据
头文件:#include<fstream>
ifstream类:用来支持从磁盘文件的输入
ofstream类:用来支持从磁盘文件的输出//ascll码流用outfile>>和outfile<<
fstream类:用来支持对磁盘文件的输入输出
ofstream outfile;//定义ofstream类outfile
outfile.open("f1.txt",ios::out)//使文件与f1.txt文件建立联系(管道)
ofstream outfile;//使用
if(!outfile.open("f1.txt",ios::out)
{//outfile.open()==0
cout<<"文件打开失败";//检测
exit(1);
}
outfile.close();
实际应用举例(提供一个基本模型)
#include<iostream>
#include<fstream>
using namespace std;
struct student
{
char name[20];
int num;
int age;
char sex;
};
int main()
{
student stud[3] = { "Li",1001,18,'f',"Fun",1002,19,'m',"Wang",1004,17,'f' };
ofstream outfile("d://stud.txt", ios::binary);//定义时告诉文件储存途径
if (!outfile)
{
cerr << "open error!" << endl;
abort();//exit(1);
}
for (int i = 0; i < 3; i++)
{
outfile.write((char*)&stud[i], sizeof(stud[i]));//用成员函数read和write读写二进制文件
outfile.close();
return 0;
}
}
高阶应用
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
int a[10];
ofstream outfile("D://f1.txt",ios::out)//定义文件流对象
if(!outfile)
{
cerr<<"open error!"<<endl;
exit(1);
}
cout<<"Enter 10 integer numbers:"<<endl;
for(int i=0;i<10;i++)
{
cin>>a[i];
outfile<<a[i]<<" ";
}
outfile.close();
return 0;
}
用成员函数write和read
ios::binary---指定为二进制文件的操作
istream &read(char *buffer,int len);
ostream &write(const char *buffer,int len);
举例:
#include<fstream>
#include<iostream>
using namespace std;
struct student
{
char name[20];
int num;
int age;
char sex;
}
int main()
{
student stud[3]={"Li",1001,18,'f',"Fun",1002,19,'m',"Wang",1004,17,'f'};
ofstream outfile("d:\\stud.txt",ios::binary);
if(!outfile)
{
cerr<<"open error!"<<endl;
abort()//或者exit(1);退出程序
}
for(int i=0;i<3;i++)
outfile.write((char*)&stud[i],sizeof(stud[i]));
//循环可以用单语句替换outfile.write((char*)&stud[0],sizeof(stud));
outfile.close();
return 0;
}
gcount():最后一次从文件中读入的字节数
tellg():读文件的文件指针的当前位置
seekg(文件中的位置):文件指针位移到指定位置准备读
seekg(位移量,参照位置):文件指针按照参照位置为基础偏移若干字节准备读
tellp():写文件的文件指针的当前位置
seekp():文件指针移到指定位置准备写
seekp(位移量,参照位置):文件指针按照参照位置偏移若干
参照位置:
ios::beg
ios::cur
ios::end
举例:infile.seekg(100)---文件指针移到100字节位置
infile.seekg(-50,ios::cur) 文件指针从当前位置后移50字节//读
outfile.seekp(-75,ios::end)---文件指针从文件末尾后移75个位置
若想保留上次存入的数据:
ofstream outfile("D://f1.txt",ios::out|ios::app);//定义文件流对象