#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方式,也不能读写二进制文件
c++的ifstream和ofstream读写类对象
最新推荐文章于 2024-08-14 22:33:49 发布