Added file2stralloc
to read a file directly into a stralloc
.
Signed-off-by: Dan Cross <patchdev@fat-dragon.org>
This commit is contained in:
parent
7986d00b71
commit
aba49d7a20
@ -406,6 +406,7 @@ extern char **split_on_space(char *str, size_t *lenp);
|
|||||||
extern void die(const char *msg);
|
extern void die(const char *msg);
|
||||||
extern void *malloz(size_t size);
|
extern void *malloz(size_t size);
|
||||||
extern char *file2str(const char *path);
|
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 *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 *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);
|
extern char *str3dup(const char *a, const char *b, const char *c);
|
||||||
|
27
src/util.c
27
src/util.c
@ -1,4 +1,5 @@
|
|||||||
#include <sys/types.h>
|
#include <sys/types.h>
|
||||||
|
#include <sys/mman.h>
|
||||||
#include <sys/stat.h>
|
#include <sys/stat.h>
|
||||||
|
|
||||||
#include <assert.h>
|
#include <assert.h>
|
||||||
@ -45,6 +46,32 @@ char *file2str(const char *path) {
|
|||||||
return contents;
|
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 *str5dup(const char *a, const char *b, const char *c, const char *d, const char *e) {
|
||||||
char *p;
|
char *p;
|
||||||
size_t alen, blen, clen, dlen, elen;
|
size_t alen, blen, clen, dlen, elen;
|
||||||
|
Reference in New Issue
Block a user