ntrncx 19 Junior Poster

i try to understand how it works.
its supposed to work but isnt.

the following code shouldnt be working?what i do wrong?

i receive the constructor values.

#include "Person.h"
#include <iostream>
#include "fstream"
#include "cstdlib"
using namespace std;

int main()
{
    fstream file("malakia.dat", ios::out | ios::in | ios::binary);
    Person data;
    
    if(!file)
    {
        cout<<"error file could not be opened";
        exit(1);
    }
           
    data.setId(1);
    data.setAge(99);
    data.setFirstName("Hello");
    data.setLastName("There");

    file.seekp((data.getId()-1)*sizeof(Person));
    file.write(reinterpret_cast <const char *>(&data),sizeof(Person));
    
    Person x;
    
    file.seekg((x.getId()-1)*sizeof(Person));
    file.read(reinterpret_cast <char *>(&x),sizeof(Person));
    
    cout<<x.getId()<<' '<<x.getFirstName()<<' '<<x.getLastName()<<' '<<x.getAge()<<endl;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.