You cannot write directly into the buffer of an std::string
, as it only ever returns char pointers that point to a read-only string1. Consider using a local array as a buffer. This is about as optimal as you can get without invoking undefined behavior.
const int BUFFER_SIZE = 1024;
char buffer[BUFFER_SIZE];
ssize_t chars_read = read(rfd, buffer, BUFFER_SIZE);
if (chars_read > 0) {
// To create a new string:
std::string read_string(buffer, chars_read);
// To populate an existing string:
existing_string.assign(buffer, chars_read);
}
1 At least pre-C++11. In C++11 it is safe to use &some_string[0]
to get a mutable pointer to the string, but you should ensure that you don't write to &some_string[some_string.size()]
or beyond, as this will invoke UB, so you would want to resize()
the string first.