C++对二进制文件的操作实例
有5个学生的数据,要求:
(1)将它们存放到磁盘文件中;
(2)将磁盘文件中的第1,3,5个学生数据读入程序,并显示出来;
(3)将第三个学生的数据修改后存回磁盘文件中的原有位置;
(4)从磁盘文件读入修改后的5个学生的数据并在屏幕输出。
为了使自己能够看懂程序,先看说明:
istream&read(char *buffer,int len);
ostream&wirte(const*char *buffer,int len);
字符指针buffer指向内存中一段存储空间,len是读写的字节数。
abort函数的作用是退出程序,与exit函数的作用相同。
seekg(位移量,参照位置);以参照位置为基础,将输入指针移动若干字节;
seekp(位移量,参照位置);以参照位置为基础,将输出指针移动若干字节;
参照位置可以是下面三个之一:
ios::beg文件开头
ios::cur指针当前位置
iod::end文件末尾
#include<fstream> #include<iostream> #include<cstdlib> #include<cstring> using namespace std; struct student { int num; char name[20]; float score; }; int main() { student stud[5]= {1001,"Li",85, 1002,"Fun",97.5, 1003,"Wang",98, 1004,"Tan",76.5, 1005,"Ling",96}; fstream iofile("stud.dat",ios::in|ios::out|ios::binary); //用fstream类定义输入输出二进制文件流对象iofile if(!iofile) { cerr<<"open error!"<<endl; abort(); } for(int i=0;i<5;i++) //像磁盘中输入5个学生的数据 { iofile.write((char *)&stud[i],sizeof(stud[i])); } student stud1[5]; //用来存放从磁盘文件读入的数据 for(int i=0;i<5;i+=2) { iofile.seekg(i*sizeof(stud[i]),ios::beg);//定位于第0,2,4学生数据开头 iofile.read((char *)&stud1[i],sizeof(stud1[0])); //先后读入3个学生的数据,存放在stud1[0], stud1[1],stud1[2]中 cout<<stud1[i].num<<" "<<stud1[i].name<<" "<<stud1[i].score<<endl; //输出 stud1[0], stud1[1],stud1[2]各成员的值 } cout<<endl; //修改第3个学生(从0开始)的数据 stud[2].num=1012; strcpy(stud[2].name,"qianshou"); stud[2].score=100; iofile.seekp(2*sizeof(stud[0]),ios::beg); //定位到第三个数据的开头 iofile.write((char *)&stud[2],sizeof(stud[2])); //更新第三个学生的数据 iofile.seekg(0,ios::beg); //从新定位于文件开头 for(int i=0;i<5;i++) { iofile.read((char *)&stud[i],sizeof(stud[i]));//读入5个学生的数据 cout<<stud[i].num<<" "<<stud[i].name<<" "<<stud[i].score<<endl; } iofile.close(); return 0; }
程序输出结果:
/* 1001 Li 85 1003 Wang 98 1005 Ling 96 1001 Li 85 1002 Fun 97.5 1012 qianshou 100 1004 Tan 76.5 1005 Ling 96 */