diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/remembering-c.c | 56 |
1 files changed, 52 insertions, 4 deletions
diff --git a/src/remembering-c.c b/src/remembering-c.c index 4484816..db65ec3 100644 --- a/src/remembering-c.c +++ b/src/remembering-c.c @@ -6,6 +6,9 @@ #include <stdio.h> #include <string.h> #include <unistd.h> +#include <libgen.h> +#include <sys/stat.h> + #ifdef TEST #include "unit-test.h" @@ -232,6 +235,31 @@ void test_get_profile_file() { } #endif +static int mkdir_p(const char *const path, mode_t mode) { + struct stat s; + int ret; + + if (stat(path, &s) == 0 && S_ISDIR(s.st_mode)) { + printf("ISDIR: %s\n", path); + return 0; + } + + char *const path_dup = strdup(path); + if (!path_dup) { + perror("mkdir_p() - strdup()"); + return -1; + } + + const char *const parent = dirname(path_dup); + if ((ret = mkdir_p(parent, mode))) { + free(path_dup); + return ret; + } + + free(path_dup); + return mkdir(path, mode); +} + int main(int argc, char *argv[]) { #ifdef TEST test_get_profile_file(); @@ -287,14 +315,34 @@ int main(int argc, char *argv[]) { return EXIT_USAGE; } - char *const profile_file = get_profile_file(profile, stderr); - if(!profile_file) { - return EXIT_ERROR; + // end getopts + + + int ret = EXIT_SUCCESS; + + char *profile_file = NULL; + if (!(profile_file = get_profile_file(profile, stderr))) { + ret = EXIT_ERROR; + goto cleanup; + } + + char *profile_file_dup = NULL; + if (!(profile_file_dup = strdup(profile_file))) { + perror("main() - strdup()"); + ret = EXIT_ERROR; + goto cleanup; + } + + if ((ret = mkdir_p(dirname(profile_file_dup), S_IRWXU | S_IRWXG | S_IRWXO))) { + goto cleanup; } printf("profile: %s\ncommand: %s\n", profile, command); printf("profile_file: %s\n", profile_file); + +cleanup: + free(profile_file_dup); free(profile_file); - return 0; + return ret; } |