数据在计算机中保存的单位是位(bit),8位组成一个字节(byte),若干个个字节组成一个纪录/域,比如学生记录:
int ID;
char name[10];
int age;
int rank[10];
将所有记录顺序地写入一个文件,生成的文件就叫顺序文件。C++标准库中,共有三个类用于文件操作,分别是ifstream、ofstream、fstream,它们统称为文件流类。
文件操作的基本流程是:1) 打开文件,2) 读/写文件,3) 关闭文件。
建立顺序文件的代码:
#include <fstream> // 包含头文件
ofstream outFile("clients.dat", ios::out|ios::binary); //打开文件
也可以先创建 ofstream对象, 再用 open函数 打开
ofstream fout;
fout.open( “test.out”, ios::out|ios::binary );
判断打开是否成功:
if(!fout) { cerr << “File open error!”<<endl; }
文件名可以给出绝对路径,也可以给相对路径;没有交代路径信息, 就是在当前文件夹下找文件。
ofstream fout(“a1.out”, ios::app);
long location = fout.tellp(); //取得写指针的位置
location = 10L;
fout.seekp(location); // 将写指针移动到第10个字节处
fout.seekp(location, ios::beg); //从头数location
fout.seekp(location, ios::cur); //从当前位置数location
fout.seekp(location, ios::end); //从尾部数location
ifstream fin(“a1.in”,ios::in);
long location = fin.tellg(); //取得读指针的位置
location = 10L;
fin.seekg(location); //将读指针移动到第10个字节处
fin.seekg(location, ios::beg); //从头数location
fin.seekg(location, ios::cur); //从当前位置数location
fin.seekg(location, ios::end); //从尾部数location
//location 可以为负值
本次程序示例中,读写的数据为Student对象。
class Student {
public:
char name[20];
int age;
};
void writeFile()
{
Student s;
ofstream outfile("student.dat", ios::out|ios::binary);
while(cin>>s.name>>s.age){
if(stricmp(s.name, "exit") == 0)
break;
outfile.write((char *)&s, sizeof(s));
}
outfile.close();
}
void readFile()
{
Student s;
ifstream infile;
infile.open("student.dat", ios::in|ios::binary);
if(!infile){
cout<<"error"<<endl;
return;
}
while(infile.read( (char *)&s, sizeof(s) )){
int readBytes = infile.gcount();
cout<<s.name<<" "<<s.age<<endl;
}
infile.close();
}
void updateFile()
{
Student s;
fstream iofile;
iofile.open("student.dat", ios::in|ios::out|ios::binary);
if(!iofile){
cout<<"error"<<endl;
return;
}
iofile.seekp(2*sizeof(s), ios::beg);
iofile.write("steven", strlen("steven")+1);
iofile.seekg(-3*sizeof(s), ios::end);
while(iofile.read( (char *)&s, sizeof(s) )){
int readBytes = iofile.gcount();
cout<<s.name<<" "<<s.age<<endl;
}
iofile.close();
}
int main(int argc, char* argv[])
{
if(argc!= 3){
cout<<"file name error"<<endl;
return 0;
}
ifstream infile(argv[1], ios::in|ios::binary);
if(!infile){
cout<<"error"<<endl;
return 0;
}
ofstream outfile(argv[2], ios::out|ios::binary);
if(!outfile){
cout<<"error"<<endl;
infile.close(); //打开的文件一定要记得关闭
return 0;
}
char c;
while(infile.get(c))
outfile.put(c);
infile.close();
outfile.close();
return 0;
}
文件的读写、修改、复制本质上都差不多,基本步骤都是1) 打开文件、2) 判断打开是否成功、3) 写文件/读文件、4)关闭文件。关键代码如下:
ofstream outfile("student.dat", ios::out|ios::binary); (或ifstream infile, ios::in) //打开文件
iofile.seekp(2*sizeof(s), ios::beg); (或iofile.seekg) //文件读写指针定位
outfile.write((char *)&s, sizeof(s)); (或infile.read) //读/写文件
iofile.close(); //关闭文件