Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Read and write multiple objects of same class

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();

Such commands are called multiple times in my program to get info of many airports. Basically the binary file is full of airports. I need to read all these airports into an array later on. How do I read the file so that I get the array of airports.

Apologies if this question is too basic. I am in high school learning about pointers and shortest path graphs.

like image 788
Rishab Mehra Avatar asked Aug 12 '13 12:08

Rishab Mehra


1 Answers

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.

like image 106
Xaqq Avatar answered Oct 29 '22 14:10

Xaqq