From f6161698827488cc21f3f3726d5af0cb2a89ce4b Mon Sep 17 00:00:00 2001 From: Martin Pärtel Date: Fri, 14 Sep 2012 16:59:49 +0300 Subject: Implemented my_dirname and added unit tests for it. --- src/misc.c | 26 ++++++++++++++++++++++++++ src/misc.h | 8 ++++++++ 2 files changed, 34 insertions(+) (limited to 'src') diff --git a/src/misc.c b/src/misc.c index c130b86..bb838c7 100644 --- a/src/misc.c +++ b/src/misc.c @@ -82,6 +82,32 @@ const char *my_basename(const char *path) return path; } +const char *my_dirname(char *path) +{ + if (strcmp(path, ".") == 0) { + return ".."; + } else if (strcmp(path, "/") == 0) { + return "/"; + } else { + int len = strlen(path); + char *p = path + len - 1; + while (p > path) { + if (*p == '/') { + break; + } + --p; + } + if (p > path) { + *p = '\0'; + return path; + } else if (*path == '/') { + return "/"; + } else { + return "."; + } + } +} + void grow_array_impl(void **array, int* capacity, int member_size) { int new_cap = *capacity; diff --git a/src/misc.h b/src/misc.h index 2ef8f6d..8b00f8d 100644 --- a/src/misc.h +++ b/src/misc.h @@ -38,6 +38,14 @@ char *strdup_until(const char *s, const char *endchars); Returns NULL if path is NULL. */ const char *my_basename(const char *path); +/* A thread-safe version of dirname, with slightly different behavior. + If path is ".", returns "..". + If path is "/", returns "/". + If path has an initial slash but no other slashes, returns "/". + If path contains a slash, replaces the last slash with a '\0' and returns path. + Otherwise, returns ".". */ +const char *my_dirname(char *path); + /* Reallocs `*array` (may be NULL) to be at least one larger than `*capacity` (may be 0) and stores the new capacity in `*capacity`. */ -- cgit v1.2.3