C++ 从文件错误中读取对象 [英] C++ Reading Objects from File Error

查看:24
本文介绍了C++ 从文件错误中读取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        fstream file;
        Patient Obj("XXX",'M',"XXX");
        file.open("Patients.dat",ios::in|ios::out|ios::app);
        file.seekg(ios::end);
        file.write((char*)&Obj,sizeof(Obj));
        file.seekg(ios::beg);


        Patient x;

        file.read((char*)&x,sizeof(x));
        x.printallInfo();

        file.close();

我正在使用此代码将对象写入文件,但是当我读取数据时 VC++ 6 崩溃并抛出异常访问冲突".(写入成功)

I'm writing objects to files using this code but when i reading data VC++ 6 Crashes and thows a exception 'Access violation' .(Writing is successful)

完整代码

#include <iostream>
#include<fstream>
#include <iomanip.h>


#include "Patient.cpp"

using namespace std;

int main(){




            fstream file;
            Patient Obj("XXX",'M',"XXX");
            file.open("Patients.dat",ios::in|ios::out|ios::app);
            file.seekg(ios::end);
            file.write((char*)&Obj,sizeof(Obj));
            file.seekg(ios::beg);


            Patient x;

            file.read((char*)&x,sizeof(x));

            file.close();


    return 0;


}

<小时>

推荐答案

这似乎是一种编组类的脆弱且不可移植的方式.您这样做的方式可能会发生的一件事是,您没有对正在序列化的数据进行深层复制.例如,如果您的 Patient 类的成员之一是 std::string,则会将裸指针写入文件,但不会写入字符串数据.更糟糕的是,当你读回它时,指针指向......某处......

That seems like a brittle and non-portable way to marshal classes. One thing that could be happening with the way you do this is that you aren't making a deep copy of the data you're serializing. for instance, if one of the members of your Patient class is a std::string, a bare pointer is written to the file, but no string data is written. Worse, when you read that back in, the pointer points... somewhere...

处理这个问题的更好方法是实际实现一个特定于类的方法,该方法确切地知道如何序列化和反序列化每个成员.

A better way to deal with this issue is to actually implement a class specific method that knows exactly how to serialize and unserialize each member.

这篇关于C++ 从文件错误中读取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆