通过C ++读取二进制文件的问题

时间:2018-02-22 18:26:56

标签: c++ binaryfiles

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

class Person{
    private :
        string name;
        int age;
    public :
        Person(string name, int age){
            this->name = name;
            this->age = age;
        }
        void show(){
            cout << "Name : " + name + "\n" << "Age : " << age << \n####################\n";
        }
        ~Person(){
            cout << "object " + name + " deleted\n";
        }
};

int main(){
    ifstream file("./files/C63.bin", ios::binary | ios::in);
    if (!file.is_open()){
        cout << "Error opening the file..\n";
    } else {
        cout << "successfully opened the file..\nThe contents of the binary file are :\n";
        Person *p;
        while (file.good()){
            file.read((char *)p, sizeof(Person));
            cout << "hi\n";
            p->show();
        }
        file.close();
    }
    return 0;
}

在代码行 - &#34; file.read((char *)p,sizeof(Person));&#34;,发生分段错误。二进制文件存在于具有几个person对象的指定位置。什么可能出错?

1 个答案:

答案 0 :(得分:1)

您已创建指向Person的指针,但未初始化它。它只是指向上帝的指针知道在哪里。因此,当您尝试从文件中读取它时,它会尝试访问无效内存,这就是段错误。

这就是你遇到段错误的原因,但正如PaulMcKenzie指出的那样,读取这样的文件只能读取字节,你可以读取一个字节或16个字节,但你仍然无法构造一个Person通过阅读原始数据来反对。我们只是说你已经为你的Person对象分配了内存,无论是malloc还是placement new或者什么东西,它只做一个浅拷贝。像std :: string这样的类有一个指向数据的指针,你只是复制指向数据的指针,而不是数据。

相关问题