C++ Read and write multiple objects of same class

你说的曾经没有我的故事 提交于 2019-12-01 05:50:01
Dmitry Ledentsov

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<airport> 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<<obj<<std::endl;

// now convert the bytes back to your objects
std::vector<airport> read_airports;
obj.convert(&read_airports);
std::cout<<read_airports.size()<<std::endl;

with the console output:

[["BLA", 1, 2], ["BLB", 3, 4]]
2

Well, if you're sure that your file is valid, then you can simply use read() until you reach EOF. Each read() - of sizeof(airport)- will give you a valid airport object.

Note that storing the binary "value" of and object will result in an invalid object when loading it if it contains pointers - or references.

EDIT: myfile.write((char*)&air,sizeof(airport); will write the content of the air object the file. By doing this, you're actually writing the object, not the pointer.

ofstream myfile;

std::vector<airport> vec;
myfile.open("rishab",ios::app||ios::binary);
while(myfile.write(reinterpret_cast<char*>(&air),sizeof(airport)) != 0)
   vec.push_back(air);

myfile.close();

Now use vec for processing

Keen

You can program it like this.

struct AirPort
{
    int a;
    int b;
    int c;
};
int main()
{
    std::vector<AirPort> airportList;
    FILE* fp = fopen(filename,"rb");
    if( NULL != fp)
    {
        while(!feof(fp))
        {
            AirPort ap;
            if (fread(&ap,sizeof(ap),1,fp)==1)
            {
                airportList.push_back(ap);
            }
        }
    }
    fclose(fp);
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!