Are you asking why the file ends up with garbage in it? That's because you allocate a C-string but don't initialize it, so it's contents are garbage. You then write that garbage to the file. Try assigning str.c_str() to buf via strcpy() or simply write() str.c_str() to the file.
termination character is needed for c strings that are not of the length of the array specified. str.c_str() fixes that delimiter (\0) to the end of the string you typed. The memory is allocated the the length, so without that termination character, you read the whole array allocation by the character array.
termination character is needed for c strings that are not of the length of the array specified.
Hm? When a C string is being read, it will happily go beyond the array bounds if no null terminator can be found, which would result in undefined behavior. And he's writing the entire string without the null terminator, regardless of how much memory the string instance has allocated internally.
const_cast should be avoided like the plague. It is only needed in some cases when calling functions of legacy libraries that don't take const pointers when they should.
In this case, it should be: constchar* buf = str.c_str();
Or just: fs.write(str.c_str(),size);