我们如何更新二进制文件呢?
还是使用上一篇博客student.dat的例子(C++ 随机访问文件)。如果我们想更新第2个学生的名字,那么我们可以使用组合模式ios::in|ios::out|ios::binary打开要更新的文件,即student.dat文件。
代码如下:
#include <iostream> #include <fstream> using namespace std; class Student { public: Student(){} Student(string name, int age, int score){ this->age = age; this->name = name; this->score = score; } int getAge() const{ return this->age; } char getName() const{ return this->name; } int getScore() const{ return this->score; } void setAge(int age){ this->age = age; } void setName(char name){ this->name = name; } void setScore(int score){ this->score = score; } private: int age; char name; int score; }; void displayStudent(const Student student){ cout << "学生" << student.getName() << "的年龄是" << student.getAge() << ", 成绩是" << student.getScore() << endl; } int main() { fstream binaryio; binaryio.open("student.dat", ios::out|ios::in|ios::binary); Student student1; binaryio.seekg(sizeof(Student)); binaryio.read(reinterpret_cast<char*>(&student1),sizeof(Student)); displayStudent(student1); student1.setName('Z'); binaryio.seekp(sizeof(Student)); binaryio.write(reinterpret_cast<char*>(&student1),sizeof(Student)); Student student2; binaryio.seekg(sizeof(Student)); binaryio.read(reinterpret_cast<char*>(&student2),sizeof(Student)); displayStudent(student2); binaryio.close(); return 0; }
运行结果: