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

    运行结果:

  • 相关阅读:
    unity3D相机缓慢看向目标物体
    设计原则
    unity3D中GUI标题内文字滚动效果
    python3.6中安装PyQt报错
    codeforces 515B.Drazil and His Happy Friends
    HDU 1029 Ignatius and the Princess IV
    POJ 1052 Plato's Blocks
    Uva220 Othello
    uva201 Squares
    uva1587 Box
  • 原文地址:https://www.cnblogs.com/bwjblogs/p/12952128.html
Copyright © 2011-2022 走看看