From aba49d7a2072330cea919693839c2394ef8937b4 Mon Sep 17 00:00:00 2001 From: Dan Cross Date: Fri, 12 Oct 2018 20:30:23 +0000 Subject: [PATCH] Added `file2stralloc` to read a file directly into a `stralloc`. Signed-off-by: Dan Cross --- src/bbs.h | 1 + src/util.c | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/bbs.h b/src/bbs.h index 5c32627..e90fc9d 100644 --- a/src/bbs.h +++ b/src/bbs.h @@ -406,6 +406,7 @@ extern char **split_on_space(char *str, size_t *lenp); extern void die(const char *msg); extern void *malloz(size_t size); extern char *file2str(const char *path); +extern stralloc file2stralloc(const char *path); extern char *str5dup(const char *a, const char *b, const char *c, const char *d, const char *e); extern char *str4dup(const char *a, const char *b, const char *c, const char *d); extern char *str3dup(const char *a, const char *b, const char *c); diff --git a/src/util.c b/src/util.c index 03b6f46..53c195f 100644 --- a/src/util.c +++ b/src/util.c @@ -1,4 +1,5 @@ #include +#include #include #include @@ -45,6 +46,32 @@ char *file2str(const char *path) { return contents; } +stralloc file2stralloc(const char *path) { + struct stat s; + int fd; + + memset(&s, 0, sizeof(s)); + if (stat(path, &s) < 0) + return EMPTY_STRALLOC; + if (!S_ISREG(s.st_mode)) + return EMPTY_STRALLOC; + fd = open(path, O_RDONLY); + if (fd < 0) + return EMPTY_STRALLOC; + size_t len = s.st_size; + char *p = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0); + if (p == NULL) { + close(fd); + return EMPTY_STRALLOC; + } + stralloc sa = EMPTY_STRALLOC; + stralloc_copyb(&sa, p, len); + munmap(fd, len); + close(fd); + + return sa; +} + char *str5dup(const char *a, const char *b, const char *c, const char *d, const char *e) { char *p; size_t alen, blen, clen, dlen, elen;