Hello I just wrote the following program to create a .dat files by enter some information and display it in the console. but in the user prompt the program crashes after print &
ItemFile.write(reinterpret_cast(&Item),sizeof(Item));
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is wrong
You cannot directly persist an object byte by byte if it contains a std::string
object. It may maintain an internal pointer to a dynamically allocated buffer on heap (where your string data are really stored) which may be dangling after reloaded.
One thing you can do is to grab the data out explicitly (use c_str()
or data()
member function) and write them to file instead of the string
object. Also, pay attention to portability issues like endianness, data size, etc for multi-byte types like int
(fixed-width integer like uint32_t
is a choice), if your program is meant to be run on different platforms.