c++的ifstream和ofstream读写类对象

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class Student
{
public:
	//有元声明最后放在public里面,不知道为啥
	friend istream& operator>>(istream&is, Student&st);
	friend ostream& operator<<(ostream&os, const Student&st);

	Student() = default;
	Student(string na, int sc)
	{
		name = na;
		score = sc;
	}
	~Student() = default;

private:
	string name;
	int score;
};

istream& operator>>(istream&is, Student&st)//ifstream是isream的子类,也能作为函数的参数
{
	is >> st.name;
	is>>st.score;
	return is;
}

ostream& operator<<(ostream&os, const Student&st)//ofstream是osream的子类,也能作为函数的参数
{
	os << st.name << " " << st.score << endl;
	return os;
}

int main()
{
     二进制文件操作

	//写文件
	//ofstream fout("student.dat",ios::binary);//能自动创建文件
	//Student  s1("李明",100);
	//fout.write((char*)&s1,sizeof(s1));
	//fout.flush();
	//fout.close();

	//读文件
	//ifstream fin("student.dat",ios::binary);
	//Student  s2; 
	//fin.read((char*)&s2, sizeof(s2));
	//fin.close();


    文本文件操作
	
	//写文件
    ofstream fout("student.txt");//能自动创建文件
	Student  s1("李明", 100);
	fout << s1;
	fout.flush();
	fout.close();

	//读文件
    ifstream fin("student.txt");
	Student  s2;
	fin >> s2;
	fin.close();

	return 0;
}

C++的ifstream和ofstream读写二进制文件只能用read和write函数吗?
用<<和>>即使指定了binary方式,也不能读写二进制文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值