#include #include #include #include #include #include "logerr.h" #include "util.h" int slurp(const char *const filename, size_t *const outlen, char **out) { int rc = -1; FILE *file = NULL; char *str = NULL; file = fopen(filename, "r"); if (file == NULL) { logerr("fopen(): %s", strerror(errno)); goto out; } if (fseek(file, 0L, SEEK_END)) { logerr("fseek(): %s", strerror(errno)); goto out; } const long lsize = ftell(file); if (lsize == -1) { logerr("ftell(): %s", strerror(errno)); goto out; } const size_t size = (size_t)lsize; errno = 0; rewind(file); if (errno) { logerr("rewind(): %s", strerror(errno)); goto out; } str = malloc(size + NULL_TERMINATOR); if (str == NULL) { logerr("malloc(): %s", strerror(errno)); goto out; } if (fread(str, sizeof(char), size, file) != size) { logerr("fread(): %s", strerror(errno)); goto out; } str[size] = '\0'; *out = str; *outlen = size; rc = 0; out: if (file != NULL) { if (fclose(file)) { logerr("fclose(): %s", strerror(errno)); rc = -1; } } if (rc) { if (str != NULL) { free(str); str = NULL; } } return rc; }