File access for serialized objects in c++

#include<iostream>
#include<fstream>
using namespace std;
//The general idea is to stream, similar to standard input and output cin/cout
// just the stream is happening in the file and not on the display

class Person
{
public:
    // Put an empty constructor to create an empty object
    Person(){};
    // pure assignment
    Person(int id,int age)
    {
        this->id = id;
        this->age = age;
    }
    // print the information
    void detail()
    {
        cout<<"id: "<<this->id<<" age: "<<this->age<<endl;
    }
private:
    int age;
    int id;
};

void serious ()
{
    //create two guys
    Person p1(1,20);
    Person p2(2,40);
    //Pay attention to the single and double quotation marks of the string
    ofstream osm("ser",ios::out|ios::binary);
    //This address must be converted to char*
    osm.write((char*)&p1,sizeof(Person));
    osm.write((char*)&p2,sizeof(Person));
    osm.close();
    
    // write first, read first
    Person p;
    ifstream ism("ser",ios::in|ios::binary);
    // don't write lvalue
    ism.read((char*)&p,sizeof(Person));
    p.detail();
    ism.read((char*)&p,sizeof(Person));
    p.detail();
    ism.close();
}

intmain()
{
    series ();
    return 0;
}

read successfully

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324610065&siteId=291194637