zoukankan      html  css  js  c++  java
  • 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;
    }

    运行结果:

  • 相关阅读:
    WPF:ListView 分组合并
    WPF:ListView 分页
    SQL
    多线程27 -- ReentrantLock
    String 对象常用方法及属性 详细介绍
    js中Array 对象方法 详细介绍
    js--运算符与或非 及 if判断条件、隐式转换 介绍
    js-函数表达式和函数声明的区别
    js预编译案例分析
    js--万物皆对象
  • 原文地址:https://www.cnblogs.com/bwjblogs/p/12952128.html
Copyright © 2011-2022 走看看