I have 2 c++ code: one is for write data into a binary file, another is for read that file.
write.cpp
code is as below:
#include
One problem is that sizeof(person.Name)
does not give what you think it does. It always gives the same size (28 bytes in my case) not matter what characters you assign to your person.Name string. This is because of std::string contains at least:
Therefore, you cannot call people.write(reinterpret_cast
. The content of your string is not located at &person
(its located wherever the pointer in std::string is pointing to)
So, what happens when you do cout << person.name << endl;
after reading it from your file? You've actually read the address (not the content) where person.name
's string pointer was pointing to, when you wrote person to people.db. This is of course not a valid memory location, after reading it from your file, again.