• C++ 更新文件


    我们如何更新二进制文件呢?

    还是使用上一篇博客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;
    }

    运行结果:

  • 相关阅读:
    TP实例化模型的两种方式 M() D()
    implode 函数 把数组拼接成字符串
    用array_search 数组中查找是否存在这个 值
    SVN-001
    PHP-006
    Access数据操作-02
    Access数据操作-01
    Html解析
    浏览器Chrome对WebGL支持判断
    浏览器渲染模式设置
  • 原文地址:https://www.cnblogs.com/bwjblogs/p/12952128.html
Copyright © 2020-2023  润新知