1. 程式人生 > >c檔案操作-二進位制檔案讀寫

c檔案操作-二進位制檔案讀寫

上次已經提到過了檔案基本分為二進位制檔案和文字檔案,文字檔案是人可以直接讀的懂的以文字的方式表達出來的檔案,二二進位制檔案則需要機器以特定的方式或者軟體來開啟,比如音訊視訊檔案都是二進位制的。

今天我們通過一個簡單的例子來了解一下二進位制檔案讀寫以及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;
	 }
 }