C++ 文件的输入与输出(二进制模式)

C++文件操作的二进制模式与文本模式类似,具体流程请查看:C++ 文件的输入与输出(文本模式)

1、写文件

ostream& write(const char*buffer,int len);
字符指针 buffer 指向内存中的一段存储空间, len 是读写的字节数。

2、读文件

istream& read( char*buffer,int len);
字符指针 buffer 指向内存中的一段存储空间, len 是读写的字节数。

案例:

不过此代码会出现运行时报错,问题尚未解决。

#include <iostream>
#include <fstream> //包含头文件
using namespace std;

class Student {
public:
	Student(){};
	Student(string name,int age):name(name),age(age){}
	void printInfo() { cout << this->name << ' ' << this->age << endl;}
private:
	string name;
	int age;
};

void outFile() {
	ofstream outf;
	Student stu("李华", 18);
	outf.open("student.txt", ios::out | ios::binary);
	outf.write((const char*)&stu, sizeof(Student));
	outf.close();
}

void inFile() {
	ifstream inf;
	Student stu;
	inf.open("student.txt", ios::in | ios::binary);
	inf.read((char*)&stu, sizeof(Student));
	inf.close();

	stu.printInfo(); //输出:李华 18
}

int main() {
	outFile();
	inFile();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值