c ++访问冲突读取位置fstream读取

时间:2015-07-20 16:19:37

标签: c++

我已经使用ofstream将字符串写入二进制文件 但是当我用fstream读取相同的二进制文件时 它出现访问冲突读取位置错误 我已经阅读了一些帖子,但我仍然无法解决我的错误

void activity::creAc(){
cout << "Activity ID : " << endl;
cin >> id;
cout << "Activity Title : " << endl;
cin >> title;
cout << "Activity Type : " << endl;
cin >> type;
cout << "Activity Date : " <<  endl;
cin >> acdate;
cout << "Activity Duration : " <<endl;
cin >> duration;
cout << "Activity Fees : " <<  endl;
cin >> fee;

}

void activity::showTask(){
cout << "Activity Title : " << title<<endl;
cout << "Activity Type : " << type << endl;
cout << "Activity Date : " << acdate << endl;
cout << "Activity Duration : " << duration << endl;
cout << "Activity Fees : " << fee << endl;

}

#include <iostream>
#include <string>
#include "user.h"
#include "Teacher.h"
#include "staff.h"
#include "activity.h"
#include <fstream>
#include <istream>
#include <ostream>
using namespace std;

void main(){
    cout << "1.Create" << endl;
    cout << "2.Read" << endl;
    int choicenum;
    cin >> choicenum;
    switch (choicenum){
    case 1: {
                activity obj;
                ofstream fp2;
                fp2.open("activity.dat", ios::binary | ios::app);
                obj.creAc();
                fp2.write((char*)&obj, sizeof(obj));
                fp2.close();
                break;
    }
    case 2:
    {
        activity obj2;
        ifstream fp1;
        fp1.open("activity.dat", ios::binary);
        while (fp1.read((char*)&obj2, sizeof(obj2))){
                obj2.showTask();
        }
        fp1.close();
    }
    default: exit(0);
    };

    system("pause");
}

2 个答案:

答案 0 :(得分:0)

像许多容器一样,

std::string实际上是一个智能指针的包装器,它指向一些根据需要动态分配的数据。

将其写入文件只会存储文件写入时的地址(加上长度等支持数据)

因此,当您回读该文件时,您将获得来自不同会话/机器/等的指针。然后,您尝试读取指向的位置,它根本不属于您的程序,因此违反了访问权限。

您需要静态分配已知长度的char,而不是需要指针的任何内容。

答案 1 :(得分:-1)

错误的声明

class activity {
    // data member is std::string.
    typedef std::string value_type;
    value_type id;
    value_type title;
    value_type type;
    value_type acdate;
    value_type duration;
    value_type fee;
public:
    void creAc();
    void showTask();
};

良好声明

class activity {
    // data member is char[64].
    typedef char value_type[64];
    value_type id;
    value_type title;
    value_type type;
    value_type acdate;
    value_type duration;
    value_type fee;
public:
    void creAc();
    void showTask();
};

您应该了解c ++类的内存布局。