954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

fstream,read,write and reinterpret_cast question

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;
}
ntrncx
Junior Poster
116 posts since Jan 2011
Reputation Points: 29
Solved Threads: 7
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You