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

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM