Well, you need to somehow create a char* , as this function requires. (By the way: you are talking about the Posix read function, not you, not std::istream::read ?) The problem is not char* , this is what char* indicates (which I suspect that you are actually business meant).
The simplest and most common solution here is to use a local array:
char buffer[43]; int len = read(fd, buffer, 42); if ( len < 0 ) { // read error... } else if ( len == 0 ) { // eof... } else { std::string data(buffer, len); }
If you want to write directly to std::string , however, this is possible (although not necessarily a good idea):
std::string data; data.resize( 42 ); int len = read( fd, &data[0], data.size() );
This avoids copying, but, frankly ... The copy is small compared to the time it takes to actually read and to allocate memory in a row. It also has a (possibly negligible) flaw in the resulting string, which has an actual buffer of 42 bytes (rounded to any), and not just the minimum required for the characters actually read.
(And since people sometimes raise the issue of memory contact in std:;string : this was a problem ten or more years ago. The original specifications for std::string were designed to allow non-contiguous implementations, according to the then-popular class rope . In practice, no developer found this to be useful, and people started to get in touch. At this point, the standardization committee decided to harmonize the standard with existing practices and require contact. So ... no implementation would ever be and adjacent and no future implementation would not contradict adjacency requirements given in C ++ 11.)
source share