diff options
| author | Russ Allbery <rra@stanford.edu> | 2008-04-24 23:05:14 +0000 | 
|---|---|---|
| committer | Russ Allbery <rra@stanford.edu> | 2008-04-24 23:05:14 +0000 | 
| commit | 86bce23e53e6cc89ed5104b21a5fe33fab5a7a9f (patch) | |
| tree | c8c352137a41c5e8da8e46dd880252a30132c89e /client/file.c | |
| parent | a93ca104c89859e1022c818579f81f528be204b5 (diff) | |
The wallet command-line client now reads the data for store from a
file (using -f) or from standard input (if -f wasn't given) when the
data isn't specified on the command line.  The data still must not
contain nul characters.
Diffstat (limited to 'client/file.c')
| -rw-r--r-- | client/file.c | 52 | 
1 files changed, 52 insertions, 0 deletions
diff --git a/client/file.c b/client/file.c index 7e0563e..c109bd5 100644 --- a/client/file.c +++ b/client/file.c @@ -11,7 +11,9 @@  #include <config.h>  #include <portable/system.h> +#include <errno.h>  #include <fcntl.h> +#include <sys/stat.h>  #include <client/internal.h>  #include <util/util.h> @@ -109,3 +111,53 @@ get_file(struct remctl *r, const char *prefix, const char *type,          free(data);      return 0;  } + + +/* + * Read all of a file into memory and return the contents as a newly allocated + * string.  Handles a file name of "-" to mean standard input.  Dies on any + * failure. + * + * This will need modification later when we want to handle nul characters. + */ +char * +read_file(const char *name) +{ +    char *contents; +    size_t size, offset; +    int fd; +    struct stat st; +    ssize_t status; + +    if (strcmp(name, "-") == 0) { +        fd = fileno(stdin); +        size = BUFSIZ; +        contents = xmalloc(size); +    } else { +        fd = open(name, O_RDONLY); +        if (fd < 0) +            sysdie("cannot open file %s", name); +        if (fstat(fd, &st) < 0) +            sysdie("cannot stat file %s", name); +        size = st.st_size + 1; +        contents = xmalloc(size); +    } +    offset = 0; +    do { +        if (offset >= size - 1) { +            size += BUFSIZ; +            contents = xrealloc(contents, size); +        } +        do { +            status = read(fd, contents + offset, size - offset - 1); +        } while (status == -1 && errno == EINTR); +        if (status < 0) +            sysdie("cannot read from file"); +        offset += status; +    } while (status > 0); +    close(fd); +    contents[offset] = '\0'; +    if (memchr(contents, '\0', offset) != NULL) +        die("cannot yet handle file data containing nul characters"); +    return contents; +}  | 
