diff options
Diffstat (limited to 'fileutils.c')
-rw-r--r-- | fileutils.c | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/fileutils.c b/fileutils.c index 137373b..ea57550 100644 --- a/fileutils.c +++ b/fileutils.c @@ -3,9 +3,12 @@ #include <stdio.h> #include <stdlib.h> +#include <string.h> #include <errno.h> #include <pwd.h> #include <unistd.h> +#include <fcntl.h> +#include <sys/stat.h> const char* get_home_dir() { const char *home_dir = getenv("HOME"); @@ -45,3 +48,35 @@ int file_get_content(const char *filepath, char **data, long *size) { fclose(file); return result; } + +int create_directory_recursive(char *path) { + int path_len = strlen(path); + char *p = path; + char *end = path + path_len; + for(;;) { + char *slash_p = strchr(p, '/'); + + // Skips first '/', we don't want to try and create the root directory + if(slash_p == path) { + ++p; + continue; + } + + if(!slash_p) + slash_p = end; + + char prev_char = *slash_p; + *slash_p = '\0'; + int err = mkdir(path, S_IRWXU); + *slash_p = prev_char; + + if(err == -1 && errno != EEXIST) + return err; + + if(slash_p == end) + break; + else + p = slash_p + 1; + } + return 0; +} |