Mercurial > hg > octave-kai > gnulib-hg
diff lib/read-file.c @ 6848:2a11dd9faacd
2006-06-19 Paul Eggert <eggert@cs.ucla.edu>
* read-file.c (fread_file): Start with buffer allocation of
0 bytes rather than 1 byte; this simplifies the code.
Don't invoke feof; it's not needed. Refactor to avoid duplicate
code to free buffer and save/restore errno.
(internal_read_file): Remove unused local.
author | Simon Josefsson <simon@josefsson.org> |
---|---|
date | Wed, 21 Jun 2006 08:02:40 +0000 (2006-06-21) |
parents | 19c37b3f23b1 |
children | a88f85e4728f |
line wrap: on
line diff
--- a/lib/read-file.c +++ b/lib/read-file.c @@ -36,16 +36,15 @@ char * fread_file (FILE * stream, size_t * length) { - char *buf = malloc (1); - size_t alloc = 1; + char *buf = NULL; + size_t alloc = 0; size_t size = 0; + int save_errno; - if (!buf) - return NULL; - - while (!feof (stream)) + for (;;) { size_t count; + size_t requested; if (size + BUFSIZ + 1 > alloc) { @@ -58,32 +57,31 @@ new_buf = realloc (buf, alloc); if (!new_buf) { - int save_errno = errno; - free (buf); - errno = save_errno; - return NULL; + save_errno = errno; + break; } buf = new_buf; } - count = fread (buf + size, 1, alloc - size - 1, stream); + requested = alloc - size - 1; + count = fread (buf + size, 1, requested, stream); size += count; - if (ferror (stream)) + if (count != requested) { - int save_errno = errno; - free (buf); - errno = save_errno; - return NULL; + save_errno = errno; + if (ferror (stream)) + break; + buf[size] = '\0'; + *length = size; + return buf; } } - buf[size] = '\0'; - - *length = size; - - return buf; + free (buf); + errno = save_errno; + return NULL; } static char * @@ -92,7 +90,6 @@ FILE *stream = fopen (filename, mode); char *out; int save_errno; - int rc; if (!stream) return NULL;