The version of the code using len
should be:
char buf[256];
int len = snprintf(buf, sizeof buf, "It was %s\r\n", weather);
if ( len < 0 || len >= sizeof buf )
// error handling, abort...
write(p->fd, buf, len);
Using sprintf
is risky as it may cause a buffer overflow if weather
is not fully under your control.
As mentioned in its documentation, the sprintf
family can return a negative value if there is an error; and the returned value can be larger than the buffer size if the write would have not fitted in the buffer.
Another option covered by other answers is to omit checking len
, and instead use strlen
to find the length to send. Some would consider that unnecessarily inefficient. Further, in that case you should really check len
anyway in case encoding fails which would result in strlen
operating on garbage.