C++学习笔记——二进制文件的读写

二进制文件的读写是以字节为单位进行操作的,举例如下:

#include<iostream>
#include<fstream>
#include<string.h> //运行strcpy函数需要此头文件
using namespace std;
class Student{
	private:
		char Name[10];
		char Class[10];
		char Sex;
		int Age;
	public:
		Student(){}
		Student(char *Name,char *Class,char sex,int age){
			strcpy(this->Name,Name);
			strcpy(this->Class,Class);
			Sex=sex;
			Age=age;
		}
		void Showme(){
			cout<<Name<<'\t'<<Class<<'\t'<<Sex<<'\t'<<Age<<endl;
		}
}; 

int main(){
	Student stu[3]={
	Student("张三","材料",'m',27),
	Student("李四","机械",'m',26),
	Student("王五","生物",'f',25)};
	//打开文件
	ofstream file1("test.dat",ios::binary);
	if(!file1) {
		cout<<"文件打开失败"<<endl;
		return 1;
	}
	//写文件 
	for(int i=0;i<3;i++){
		file1.write((char *)&stu[i],sizeof(stu[i]));
	}
	file1.close();
	//打开文件
	ifstream file2("test.dat",ios::binary);
	if(!file2) {
		cout<<"文件打开失败"<<endl;
		return 1;
	}
	//读文件
	Student stu2;
	while(file2){
		file2.read((char *)&stu2,sizeof(stu2));
		if (file2) stu2.Showme();
	}
	file2.close();
	return 0;
}

运行结果:
张三 材料 m 27
李四 机械 m 26
王五 生物 f 25

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值