I have two questions with reading / writing complex data in a binary file. I have this code which saves a complex type (struct) in a binary file.
#1 : How does the system know the correct size of DATA for the calls to read() and write()? My understading is the objects of type std::string can have a different size depending on the data that it contains.Code:#include <iostream> #include <string> #include <fstream> struct DATA { std::string s1; std::string s2; int i1; int i2; std::string s3; double d1; double d2; std::string s4; }; void Save(DATA &d) { std::ofstream oFile("data.bin", std::ios::out | std::ios::binary); oFile.write( (char*)&d, sizeof(d) ); oFile.close(); return; } void Load(DATA &d) { std::ifstream iFile("data.bin", std::ios::in | std::ios::binary); iFile.read( (char*)&d, sizeof(d) ); iFile.close(); return; } void Display(DATA &d) { std::cout<<"string 1 = " <<d.s1 <<"\n" <<"string 2 = " <<d.s2 <<"\n" <<"integer 1 = " <<d.i1 <<"\n" <<"integer 2 = " <<d.i2 <<"\n" <<"string 3 = " <<d.s3 <<"\n" <<"double 1 = " <<d.d1 <<"\n" <<"double 2 = " <<d.d2 <<"\n" <<"string 4 = " <<d.s4 <<"\n\n\n\n"; return; } int main() { DATA x, y; x.s1 = "This is some text"; x.s2 = "This is some more text"; x.i1 = 5; x.i2 = 55423; x.s3 = "And some more text"; x.d1 = 87.12; x.d2 = 1123.542; x.s4 = "Wait! Here's some more text!!"; Display(x); Save(x); Load(y); Display(y); return 0; }
#2 : Is this legal / safe?