From ae71a09d376d4b435e2290cda48dffa96d54b16b Mon Sep 17 00:00:00 2001 From: mrb0nk500 Date: Sun, 31 Jul 2022 17:43:23 -0300 Subject: 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. --- misc.c | 36 ++++++++++++++++++++++++++++++++++++ misc.h | 2 ++ 2 files changed, 38 insertions(+) diff --git a/misc.c b/misc.c index 97333eb..4c0cab0 100644 --- a/misc.c +++ b/misc.c @@ -1,8 +1,11 @@ #include +#include #include #include #include #include +#include +#include #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); +} diff --git a/misc.h b/misc.h index 0ad5fba..3a653e2 100644 --- a/misc.h +++ b/misc.h @@ -17,4 +17,6 @@ extern char *create_num_str(const char *str, int num); extern int is_empty(const char *str); extern char *skip_whitespace(const char *str); extern int format_len(const char *fmt, ...); +extern int is_dir(const char *path); +extern void mkdirp(const char *path, int mode); #endif -- cgit v1.2.3-13-gbd6f