diff options
| author | Nicholas Rodrigues Lordello <[email protected]> | 2026-09-07 14:29:15 +0200 |
|---|---|---|
| committer | Nicholas Rodrigues Lordello <[email protected]> | 2026-09-07 14:29:15 +0200 |
| commit | bdb6f60511a063855bcab6cec206306b92b32edd (patch) | |
| tree | 8c7204504f4aa3270f8424c8103c310af17e0902 | |
| parent | 5f48411161d243627ff3b521250c74d40d776bc3 (diff) | |
Add File System Utilities
We take a slightly different API approach where we return an error
number and other values are "returned" through pointers that are
passed into the function.
Other functions will be adapted to use this pattern going forward.
| -rw-r--r-- | src/dbx.h | 3 | ||||
| -rw-r--r-- | src/fs.c | 101 |
2 files changed, 104 insertions, 0 deletions
@@ -11,6 +11,9 @@ #define COUNTOF(x) ((sizeof(x)) / (sizeof(*x))) #define HOSTNAME_MAX _POSIX_HOST_NAME_MAX +int dbx_writefile(const char *file, const char *format, ...); +int dbx_readfile(const char *file, char **contents); + void dbx_printerr(const char *format, ...); void dbx_perror(const char *s, int e); int dbx_fpath(char path[PATH_MAX], const char *format, ...); diff --git a/src/fs.c b/src/fs.c new file mode 100644 index 0000000..aea43e3 --- /dev/null +++ b/src/fs.c @@ -0,0 +1,101 @@ +#include <errno.h> +#include <stdarg.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> + +#include "dbx.h" + +int dbx_writefile(const char *file, const char *format, ...) { + if (file == NULL || format == NULL) { + return EINVAL; + } + + FILE *f = fopen(file, "w"); + if (f == NULL) { + goto error; + } + + errno = 0; + va_list ap; + va_start(ap, format); + int n = vfprintf(f, format, ap); + va_end(ap); + + if (n < 0) { + goto error; + } + if (fclose(f) != 0) { + f = NULL; + goto error; + } + + return 0; + +error:; + int result = errno; + if (result == 0) { + result = EIO; + } + + if (f != NULL) { + fclose(f); + } + return result; +} + +int dbx_readfile(const char *file, char **contents) { + if (file == NULL || contents == NULL) { + return EINVAL; + } + + char *buf = NULL; + FILE *f = fopen(file, "r"); + if (f == NULL) { + goto error; + } + + size_t end; + { + long endl; + if (fseek(f, 0, SEEK_END) || (endl = ftell(f)) < 0 || + fseek(f, 0, SEEK_SET)) { + goto error; + } + if (endl >= SIZE_MAX) { + errno = ENOMEM; + goto error; + } + end = (size_t)endl; + } + + buf = malloc(end + 1); + if (buf == NULL) { + goto error; + } + + errno = 0; + if (fread(buf, 1, end, f) != end) { + goto error; + } + if (fclose(f) != 0) { + f = NULL; + goto error; + } + + buf[end] = '\0'; + *contents = buf; + return 0; + +error:; + int result = errno; + if (result == 0) { + result = EIO; + } + + if (f != NULL) { + fclose(f); + } + free(buf); + return result; +} |
