diff options
author | Niels Möller <nisse@lysator.liu.se> | 2012-09-10 21:54:24 +0200 |
---|---|---|
committer | Niels Möller <nisse@lysator.liu.se> | 2012-09-10 21:54:24 +0200 |
commit | 2bd9d1b8703e57eeb955c16f482555abe6315a4d (patch) | |
tree | b242c5a5e7411efa0b7e049b0baab70ff24ae5f3 /examples | |
parent | 3ead2b978cb8bff337f3ae659d315da483525ab7 (diff) | |
download | nettle-2bd9d1b8703e57eeb955c16f482555abe6315a4d.tar.gz |
Reorganized read_file loop.
Diffstat (limited to 'examples')
-rw-r--r-- | examples/io.c | 39 | ||||
-rw-r--r-- | examples/io.h | 7 |
2 files changed, 27 insertions, 19 deletions
diff --git a/examples/io.c b/examples/io.c index 7b2289cc..2eab7e0c 100644 --- a/examples/io.c +++ b/examples/io.c @@ -71,8 +71,7 @@ werror(const char *format, ...) unsigned read_file(const char *name, unsigned max_size, char **contents) { - unsigned size; - unsigned done; + unsigned size, done; char *buffer; FILE *f; @@ -82,21 +81,10 @@ read_file(const char *name, unsigned max_size, char **contents) werror("Opening `%s' failed: %s\n", name, strerror(errno)); return 0; } - buffer = NULL; - if (max_size && max_size < 100) - size = max_size; - else - size = 100; - - /* FIXME: The use of feof and ferror in this loop is a bit confused - (but I think it is still correct). We should check the return - value of fread, and call feof and/or ferror when we get a short - item count. */ + size = 100; - for (done = 0; - (!max_size || done < max_size) && !feof(f); - size *= 2) + for (buffer = NULL, done = 0;; size *= 2) { char *p; @@ -118,8 +106,25 @@ read_file(const char *name, unsigned max_size, char **contents) buffer = p; done += fread(buffer + done, 1, size - done, f); - if (ferror(f)) - goto fail; + if (done < size) + { + /* Short count means EOF or read error */ + if (ferror(f)) + { + fprintf (stderr, "Reading `%s' failed: %s\n", + name, strerror(errno)); + + goto fail; + } + if (done == 0) + /* Treat empty file as error */ + goto fail; + + break; + } + + if (size == max_size) + break; } fclose(f); diff --git a/examples/io.h b/examples/io.h index d95c81a3..f79855da 100644 --- a/examples/io.h +++ b/examples/io.h @@ -39,8 +39,11 @@ xalloc(size_t size); void werror(const char *format, ...) PRINTF_STYLE(1, 2); -/* If size is > 0, read at most that many bytes. If size == 0, - * read until EOF. Allocates the buffer dynamically. */ +/* If size is > 0, read at most that many bytes. If size == 0, read + * until EOF. Allocates the buffer dynamically. An empty file is + * treated as an error; return value is zero, and no space is + * allocated. The returned data is NUL-terminated, for convenience. */ + unsigned read_file(const char *name, unsigned size, char **buffer); |