C++ Read and write multiple objects of same class

前端 未结 4 836
故里飘歌
故里飘歌 2021-01-13 06:52
airport air(1,2,3); //an airport constructor
ofstream myfile;
myfile.open(\"rishab\",ios::app||ios::binary);
myfile.write((char*)air,sizeof(airport);
myfile.close();         


        
4条回答
  •  余生分开走
    2021-01-13 07:36

    What you are trying to do is serialization. This way of serializing objects is not stable, and highly depends on what airport is. It's better to use explicit serialization.

    Here's a description of what serialization is and why is it made this way.

    In MessagePack a typical serialization-deserialization scenario would look like this:

    struct airport {
     std::string name; //you can name your airports here
     int planeCapacity;
     int acceptPlanesFrom;
     MSGPACK_DEFINE(name,planeCapacity,acceptPlanesFrom);
    };
    

    ...

    // define your airports
    std::vector airports;
    airport a={"BLA",1,2};
    airport b={"BLB",3,4};
    airports.push_back(a);
    airports.push_back(b);
    
    // create a platform-independent byte sequence from your data
    msgpack::sbuffer sbuf;
    msgpack::pack(sbuf, airports) ;
    std::string data=sbuf.data();//you can write that into a file
    
    msgpack::unpacked msg;
    // get your data safely back
    msgpack::unpack(&msg, sbuf.data(), sbuf.size());
    msgpack::object obj = msg.get();
    
    std::cout< read_airports;
    obj.convert(&read_airports);
    std::cout<

    with the console output:

    [["BLA", 1, 2], ["BLB", 3, 4]]
    2
    
    • some more

提交回复
热议问题