What I want to do finally, is read a complete (binary) file into a
string and then send this via using socket to/from server.
I am using socket-routines that use strings because it is much easier
this way and I would love to leave it at that and not recode
everything...
OK, in case of large and/or binary strings assign(), append() and swap()
member functions are your friends. E.g.
void read_from_file(std::string& content) {
char buffer[N];
std::string collector;
while(!eof(the_file)) {
// ... read chunk of file into the buffer, say of length n.
collector.append(buffer, n);
}
content.swap(collector);
}
void send_to_socket() {
std::string packet;
read_from_file(packet);
// assume there is a nice C++ object around called socket:
socket.write(packet.data(), packet.length());
}
Note that using c_str() instead of data() might imply a performance
penalty here as the c_str() function might have to add a NUL terminator
at the end of the buffer, which can cause a reallocation and extra
unneeded copy of the whole string. As you must be managing the lengths
anyway explicitly the terminating NUL is not needed.
OK, swap() is not really necessary in this example, but it might be
useful in other similar situations where you have a large string to be
passed around.
In case of binary data the first rule is to avoid all std::string member
functions which take a single char* pointer - there is no way to specify
the actual length of data for such parameter.
HTH
Paavo