user1803967
user1803967

Reputation: 21

Reading objects from file and getting error

(This is a homework project.) I am trying to write objects from class A (Contains couple of strings and ints, also a list from objects from class B ) into file. Then I have to read back these objects from the file and display their content. I am using this code:

Writing:

ofstream ofs("filestorage.bin", ios::app|ios::binary);
A d;
ofs.write((char *)&d, sizeof(d));
ofs.close();

Reading:

ifstream ifs("filestorage.bin", ios::binary);
A e(1);

while(ifs.read((char *)&e, sizeof(e))) {    
    cout<<e;
}

ifs.close();

<< is already redefined.

It writes the data into the file, then reads it back, displays everything I want but in the end I'm getting a nice fat "Access Violation " Error. I also tried to write and read simple variables into the file (like ints). That works fine; but when I try to read an object or string I get "Access Violation". The writing seams to be OK because I get no errors.

Can you tell me why this is happening and how can I fix it? If it is necessary I can post my A and B classes too. Thanks!

Upvotes: 0

Views: 156

Answers (2)

andre
andre

Reputation: 7249

Implement the two operators << and >> for your class.

class A {
    int a;
    string s;
pubilc:
    friend ostream& operator<< (ostream& out, A& a ) {
        out << a.a << endl;
        out << a.s << endl;
    }
    friend istream& operator>> (istream& is, A& a ) {
        //check that the stream is valid and handle appropriately.
        is >> a.a; 
        is >> a.s;
    }
};

Write:

A b;
ofstream ofs("filestorage.bin", ios::app|ios::binary);
ofs << b;

Read:

fstream ifs("filestorage.bin", ios::binary);
A b;
ifs >> b;

Upvotes: 1

MaximR
MaximR

Reputation: 279

You can try just checking the stream status

while(ifs.read((char *)&e, sizeof(e)).good()){
     cout<<e;
}

Upvotes: 0

Related Questions