C++ Read and write multiple objects of same class

前端 未结 4 855
故里飘歌
故里飘歌 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:47

    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.

提交回复
热议问题