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;