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;
}
6535

被折叠的 条评论
为什么被折叠?



