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

奇点
#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;
}

在代码行 - “file.read((char *)p, sizeof(Person));”,出现分段错误。二进制文件存在于指定位置,并带有几个人物对象。可能出了什么问题?

斑马鱼

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章