write and read string to binary file C++

To write a std::string to a binary file, you need to save the string length first:

std::string str("whatever");
size_t size=str.size();
outfile.write(&size,sizeof(size));
outfile.write(&str[0],size);

To read it in, reverse the process, resizing the string first so you will have enough space:

std::string str;
size_t size;
infile.read(&size, sizeof(size));
str.resize(size);
infile.read(&str[0], size);

Because strings have a variable size, unless you put that size in the file you will not be able to retrieve it correctly. You could rely on the ‘\0’ marker that is guaranteed to be at the end of a c-string or the equivalent string::c_str() call, but that is not a good idea because

  1. you have to read in the string character by character checking for the null
  2. a std::string can legitimately contain a null byte (although it really shouldn’t because calls to c_str() are then confusing).

Leave a Comment