C++的二进制文件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++的二进制文件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1906字,纯文字阅读大概需要3分钟。
内容图文
![C++的二进制文件](/upload/InfoBanner/zyjiaocheng/836/4815405d49094a39964f506e6699157e.jpg)
C++的二进制文件读写
ios::app|ios::binary表示打开二进制文件进行追加
预处理文件
和类的新建
#include<iostream> #include<fstream> #include<string> using namespace std; class student { public: int Num; char Name[10]; int Cla; char Sex; int Age; float Chiness,Math,English; char Info[40]; void init(student *stu,int n); void write(); void display(); };
类中方法的定义--写
void student::init(student *stu,int n) { cout<<"--init student --"<<endl; ofstream fout("f1.dat",ios::binary); for(int i=0;i<n;i++) { fout.write((char*)(&stu[i]),sizeof(student)); }fout.close(); } void student::write() { cout<<"--从键盘中输入学生信息,然后追加到二进制文件中--"<<endl; ofstream fout("f1.dat",ios::app|ios::binary); cout<<"input data :"<<endl; cin>>Num; cin>>Name; cin>>Cla; cin>>Sex; cin>>Age; cin>>Chiness; cin>>Math; cin>>English; cin>>Info; fout.write((char*)(this),sizeof(*this)); //类是应用引用类型 fout.close(); }
类中方法的定义--读
void student::display() { student stu; cout<<"dispaly "<<endl; ifstream fin("f1.dat",ios::binary); fin.read((char*)(&stu),sizeof(student)); //读出二进制文件的第一个学生数据 while(!fin.eof()) { cout<<stu.Num<<endl; //元友类操作符 << 的应用 fin.read((char*)(&stu),sizeof(student)); //读出二进制文件的第一个学生数据 } fin.close(); }
类中方法的定义--查找
int search1(int num1) { student stu; cout<<"search the num of student "<<endl; ifstream fin("f1.dat",ios::binary); fin.read((char*)(&stu),sizeof(student)); while(!fin.eof()) { if(stu.Num==num1) //search successfully { cout<<stu.Num<<" "<<stu.Name<<endl; fin.close(); return 1; } fin.read((char*)(&stu),sizeof(student)); } fin.close(); cout<<"fail "<<endl; return 0; }
主函数的启用
int main () { const int n=3; student stu[n]= { {6007701,"liyi",6,'m',16,88,99,89,"a good student"}, {6007702,"wanger",6,'m',16,88,99,89,"a good student"}, {6007703,"zhangsan",6,'m',16,88,99,89,"a good student"} }; student ss; ss.init(stu,n); ss.display(); ss.write(); ss.display(); search1(6007701); return 0; }
内容总结
以上是互联网集市为您收集整理的C++的二进制文件全部内容,希望文章能够帮你解决C++的二进制文件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。