commit 42d666065f92bc9f92ecdb98952019753b3c4bac
parent ba5400a9eec60ae4eb69cff1ee6224b2c8df765c
Author: Nihal Jere <nihal@nihaljere.xyz>
Date: Wed, 17 Feb 2021 19:05:06 -0600
util.*: add mkdirs and strrepl
mkdirs creates a directory given a path, creating parent directories as
needed (like mkdir -p)
strrepl substitutes a character in a string with another, and is used in
mkdirs
Diffstat:
M | util.c | | | 36 | ++++++++++++++++++++++++++++++++++++ |
M | util.h | | | 2 | ++ |
2 files changed, 38 insertions(+), 0 deletions(-)
diff --git a/util.c b/util.c
@@ -1,4 +1,7 @@
/* See LICENSE file for copyright and license details. */
+#include <errno.h>
+#include <sys/stat.h>
+#include <sys/types.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
@@ -56,3 +59,36 @@ vstrcmp(const void *p1, const void *p2)
return strcmp((const char *) p1, (const char *) p2);
}
+/* replace occurences of a with b in str, starting from end */
+int
+strrepl(char *str, const char a, const char b)
+{
+ for (char *p = str + strlen(str); p >= str; p--) {
+ if (*p == a)
+ *p = b;
+ }
+}
+
+/* essentially mkdir -p */
+int
+mkdirs(const char *path)
+{
+ size_t len = strlen(path);
+ char dir[len];
+ char *end = dir;
+
+ strcpy(dir, path);
+ /* dir+1 to avoid removing leading /, and mkdir erroring out */
+ strrepl(dir+1, '/', 0);
+
+ do {
+ if (*end == 0) {
+ if (mkdir(dir, S_IRWXU) == -1 && errno != EEXIST)
+ die("%s: %s:", __func__, path);
+ *end = '/';
+ }
+
+ } while (end++ < dir+len);
+
+ return 0;
+}
diff --git a/util.h b/util.h
@@ -14,5 +14,7 @@ extern char *argv0;
void warn(const char *, ...);
void die(const char *, ...);
int vstrcmp(const void *p1, const void *p2);
+int strrepl(char *str, const char a, const char b);
+int mkdirs(const char *path);
#endif /* UTIL_H */