This is a function that reads until EOF and reallocs as it goes.
char *
read_to_end(int fd, int *bread)
{
ssize_t size, nread, rc;
char *buf, *tmp;
nread = 0;
size = MINLEN;
buf = malloc(size);
while ((rc = read(fd, buf + nread, size - nread))) {
if (rc < 0) {
if (errno == EINTR)
continue;
goto error;
}
nread += rc;
/* See if we need to expand. */
if (size - nread < MINLEN) {
size *= 2;
/* Make sure realloc doesn't fail. */
if (!(tmp = realloc(buf, size)))
goto error;
buf = tmp;
}
}
/* Shrink if necessary. */
if (size != nread && !(tmp = realloc(buf, nread)))
goto error;
buf = tmp;
*bread = nread;
return buf;
error:
free(buf);
return NULL;
}
Do you have any improvement suggestions?