From 145f63d5cda9d11fc8391548e7a953ec212207d4 Mon Sep 17 00:00:00 2001 From: EuAndreh Date: Sun, 27 Jun 2021 12:24:00 -0300 Subject: src/remembering-c.c: Add mkdir_p --- src/remembering-c.c | 56 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 4 deletions(-) (limited to 'src/remembering-c.c') 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 #include #include +#include +#include + #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; } -- cgit v1.2.3