diff options
author | mrb0nk500 <b0nk@b0nk.xyz> | 2022-07-31 17:43:23 -0300 |
---|---|---|
committer | mrb0nk500 <b0nk@b0nk.xyz> | 2022-07-31 17:43:23 -0300 |
commit | ae71a09d376d4b435e2290cda48dffa96d54b16b (patch) | |
tree | 282a550f86b5b05bcb66ece3ed1f15e1210718c9 /misc.c | |
parent | 300d834e9151637962d36df1ba650fbf1666c722 (diff) |
misc: Add `is_dir()`, and `mkdirp()`
`is_dir()` checks if the supplied path is a directory, and returns 1 if
it's a directory, 0 if it isn't a directory, and -1 if it doesn't exist.
`mkdirp()` works like `mkdir()` except that it also creates parent
directories if needed.
Diffstat (limited to 'misc.c')
-rw-r--r-- | misc.c | 36 |
1 files changed, 36 insertions, 0 deletions
@@ -1,8 +1,11 @@ #include <ctype.h> +#include <dirent.h> #include <string.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> +#include <sys/stat.h> +#include <unistd.h> #include "misc.h" char *read_file(const char *filename, long *size) { @@ -206,3 +209,36 @@ int format_len(const char *fmt, ...) { va_end(args); return len; } + +int is_dir(const char *path) { + DIR *dir; + + if (!access(path, F_OK)) { + if ((dir = opendir(path)) != NULL) { + closedir(dir); + return 1; + } else { + return 0; + } + } else { + return -1; + } +} + +void mkdirp(const char *path, int mode) { + char *str = make_str(path); + + for (char *p = find_delm(str, "/", *str == '/'); !is_empty(p); p = find_delm(p, "/", 1)) { + if (*p == '/') { + *p = '\0'; + } + if (is_dir(str) < 0 && mkdir(str, mode) < 0) { + break; + } + if (*p == '\0') { + *p = '/'; + } + } + + free(str); +} |