To write the std :: string file to a binary file, you must first save the length of the string:
std::string str("whatever"); size_t size=str.size(); outfile.write(&size,sizeof(size); outfile.write(&str[0],size);
To read it, cancel the process by first resizing the line so that you have enough space:
std::string str; size_t size; infile.read(&size, sizeof(size)); str.resize(size); infile.read(&str[0], size);
Since strings are of variable size, if you did not put this size in the file, you cannot get it correctly. You can rely on the token '\ 0', which is guaranteed to be at the end of line c or the equivalent line :: c_str (), but this is not a good idea, because 1. you must read the character that checks the value in the string character null 2. a std :: string can legitimately contain a null byte (although this is really not the case because the calls to c_str () are then confused).
source share