diff options
Diffstat (limited to 'src/util.c')
-rw-r--r-- | src/util.c | 74 |
1 files changed, 74 insertions, 0 deletions
diff --git a/src/util.c b/src/util.c new file mode 100644 index 0000000..3d56c14 --- /dev/null +++ b/src/util.c @@ -0,0 +1,74 @@ +#include "config.h" + +#include <errno.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "util.h" +#include "logerr.h" + + +static const size_t +NULL_TERMINATOR = sizeof((char)'\0'); + +int +slurp(const char *const filename, char **out) { + int rc = -1; + + FILE *file = NULL; + char *str = NULL; + + file = fopen(filename, "r"); + if (file == NULL) { + logerr("fopen(\"%s\"): %s\n", filename, strerror(errno)); + goto out; + } + + if (fseek(file, 0L, SEEK_END)) { + logerr("fseek(): %s\n", strerror(errno)); + goto out; + } + + const long lsize = ftell(file); + if (lsize == -1) { + logerr("ftell(): %s\n", strerror(errno)); + goto out; + } + const size_t size = (size_t)lsize; + + errno = 0; + rewind(file); + if (errno) { + logerr("rewind(file): %s\n", strerror(errno)); + goto out; + } + + str = malloc(size + NULL_TERMINATOR); + if (str == NULL) { + logerr("malloc(%ld): %s\n", size + NULL_TERMINATOR, strerror(errno)); + goto out; + } + + if (fread(str, sizeof(char), size, file) != size) { + logerr("fread(\"%s\"): %s\n", filename, strerror(errno)); + goto out; + } + str[size] = '\0'; + *out = str; + + rc = 0; +out: + if (file != NULL) { + if (fclose(file)) { + logerr("fclose(\"%s\"): %s\n", filename, strerror(errno)); + rc = -1; + } + } + if (rc) { + if (str != NULL) { + free(str); + } + } + return rc; +} |