上次已经提到过了文件基本分为二进制文件和文本文件,文本文件是人可以直接读的懂的以文字的方式表达出来的文件,二二进制文件则需要机器以特定的方式或者软件来打开,比如音频视频文件都是二进制的。
今天我们通过一个简单的例子来了解一下二进制文件读写以及fseek()函数的使用:
#include <iostream>
using namespace std;
struct student
{
int number;
char name[];
};
void getdata(student stu[],int number)
{
for(int i=0;i<number;i++)
{
cout<<"the "<<i+1<<" student:"<<endl;
cout<<"please cin number of sstudent:";
cin>>stu[i].number;
cout<<"please cin name of student:";
cin>>stu[i].name;
}
}
int savedata(student stu[],int number)
{
int ret=-1;
FILE *fp=fopen("student.data","w");
if(fp)
{
ret=fwrite(stu,sizeof(student),number,fp);
fclose(fp);
}
return ret==number;
}
void read(FILE* fp,int index);
void seek(void)
{
FILE* fp=fopen("student.data","r");
if(fp)
{
cout<<"fopen in seek()"<<endl;
fseek(fp,0L,SEEK_END);
long size=ftell(fp);
int number=size/sizeof(student);
int index=0;
cout<<"There are "<<number<<" students,which one do you want to view?";
cin>>index;
index--;
read(fp,index);
fclose(fp);
}
else cout<<"open failed of fopen!";
}
int main()
{
int num;
cout<<"please input the number of students:";
cin>>num;
student stu[num];
getdata(stu,num);
if(savedata(stu,num))
cout<<"save succeded!";
seek();
}
void read(FILE* fp,int index)
{
fseek(fp,index*sizeof(student),SEEK_SET);
student stu;
if(fread(&stu,sizeof(student),1,fp)==1)
{
cout<<"the "<<index+1<<"student:"<<endl;
cout<<stu.number<<" "<<stu.name;
}
}