read structured binary file c++

前端 未结 1 1266
暖寄归人
暖寄归人 2021-01-25 19:12

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 &

1条回答
  •  时光说笑
    2021-01-25 20:11

    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.

    0 讨论(0)
提交回复
热议问题