From 68b01ce93edc44ba60f97b183424f5d7e23a1cc5 Mon Sep 17 00:00:00 2001 From: Denis Kenzior Date: Tue, 16 Mar 2010 17:19:01 -0500 Subject: [PATCH] Refactor: create_dirs logic - Remove reference to g_malloc and replace with g_try_malloc - Be extra pedantic on the inputs - Refactor the logic to make it slightly easier to follow --- src/storage.c | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/storage.c b/src/storage.c index 300c6eb..618c111 100644 --- a/src/storage.c +++ b/src/storage.c @@ -42,22 +42,31 @@ int create_dirs(const char *filename, const mode_t mode) const char *prev, *next; int err; + if (filename[0] != '/') + return -1; + err = stat(filename, &st); if (!err && S_ISREG(st.st_mode)) return 0; - dir = g_malloc(strlen(filename) + 1); + dir = g_try_malloc(strlen(filename) + 1); + if (dir == NULL) + return -1; + strcpy(dir, "/"); - for (prev = filename; (next = strchr(prev + 1, '/')); prev = next) - if (next > prev + 1) { - strncat(dir, prev + 1, next - prev); + for (prev = filename; (next = strchr(prev + 1, '/')); prev = next) { + /* Skip consecutive '/' characters */ + if (next - prev == 1) + continue; + + strncat(dir, prev + 1, next - prev); - if (mkdir(dir, mode) && errno != EEXIST) { - g_free(dir); - return -1; - } + if (mkdir(dir, mode) == -1 && errno != EEXIST) { + g_free(dir); + return -1; } + } g_free(dir); return 0; -- 2.7.4