Problem with fstream class in c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Problem with fstream class in c++

Hi. I'm trying to use these 2 codes: 1: #include <fstream> #include <iostream> using namespace std; struct student{ string name; }; int main(){ ofstream fs; fs.open("Simpletest.bin"); student a; a.name = "A"; fs.write((char *)&a , sizeof(a)); fs.close(); return 0; } 2: #include <fstream> #include <iostream> using namespace std; struct student{ string name; }; int main(){ student a; ifstream fp; fp.open("Simpletest.bin"); fp.read((char*) &a , sizeof(a)); if (fp.is_open()) cout << a.name; } I expected the second one prints "A" but it prints something unusual.Can you please help me to find out what probmlems does it have?

5th Jun 2019, 8:14 PM
Sobhan Safdariyan
Sobhan Safdariyan - avatar
1 Answer
+ 4
Yea... You can only do this with build-in types that do not work with pointers internally. However std::string does use pointers internally and by writing it to a file in this manner you also write this pointer, that is pointing somewhere on the heap ( usually ), to the file. When the program exits, this heap allocated data will be deleted and when you then read from the file again it writes the old pointer back into std::string. But this time without that data actually being allocated to your program, at this point anything could happen. Even if it was allocated, the value probably wouldn't be the same again. Even if it wasn't pointing to the heap but to some location on the stack instead, you'd also run into problems because that value at that address won't be there the next time either. reinterpret_casts are extremely dangerous to use so you probably shouldn't unless you know exactly what you're doing. What you are doing is called 'serialization' and '(un/de)serialization' and is far from a trivial thing to implement ( correctly ). https://isocpp.org/wiki/faq/serialization ( google for more information ) Probably the easiest way would be to create an interface with a virtual serialize and deserialize function and have the classes inherit from it and custom implement it for each class. But even this can be very difficult to get working correctly and there are better ways, but are even harder to get working.
5th Jun 2019, 9:22 PM
Dennis
Dennis - avatar