diff options
author | EuAndreh <eu@euandre.org> | 2024-04-07 11:49:25 -0300 |
---|---|---|
committer | EuAndreh <eu@euandre.org> | 2024-04-07 11:49:25 -0300 |
commit | 381492a000454822398a8737c73ea586464ee56a (patch) | |
tree | 9e28124ba2373b157356f0d5172b60009a20041e /src/util.c | |
parent | src/lib.c: Print project metadata on pindaiba_main (diff) | |
download | pindaiba-381492a000454822398a8737c73ea586464ee56a.tar.gz pindaiba-381492a000454822398a8737c73ea586464ee56a.tar.xz |
src/util.c: Add slurp(), with a simple test
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; +} |