Browse Source

base: Add faux_mkdir_p()

Serj Kalichev 1 year ago
parent
commit
0086c52186
3 changed files with 40 additions and 0 deletions
  1. 38 0
      faux/base/fs.c
  2. 1 0
      faux/faux.h
  3. 1 0
      faux/faux.map

+ 38 - 0
faux/base/fs.c

@@ -12,6 +12,7 @@
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
+#include <libgen.h>
 
 #include "faux/str.h"
 
@@ -155,6 +156,43 @@ bool_t faux_rm(const char *path)
 }
 
 
+/** @brief Make dir with parents.
+ *
+ * This is the same as mkdir -p.
+ *
+ * @param [in] path Directory to create.
+ * @param [in] mode Mode of newly created dir.
+ * @return BOOL_TRUE - success, BOOL_FALSE on error.
+ */
+bool_t faux_mkdir_p(const char *path, mode_t mode)
+{
+	char *dir_d = NULL;
+	char *dname = NULL;
+
+	assert(path);
+	if (!path)
+		return BOOL_FALSE;
+
+	// Already exists
+	if (faux_isdir(path))
+		return BOOL_TRUE;
+
+	// Get dirname
+	dir_d = faux_str_dup(path);
+	dname = dirname(dir_d);
+	if (!faux_mkdir_p(dname, mode)) {
+		faux_str_free(dir_d);
+		return BOOL_FALSE;
+	}
+	faux_str_free(dir_d);
+
+	if (mkdir(path, mode) < 0)
+		return BOOL_FALSE;
+
+	return BOOL_TRUE;
+}
+
+
 /** @brief Expand tilde within path due to HOME env var.
  *
  * If first character of path is tilde then expand it to value of

+ 1 - 0
faux/faux.h

@@ -100,6 +100,7 @@ ssize_t faux_filesize(const char *path);
 bool_t faux_isdir(const char *path);
 bool_t faux_isfile(const char *path);
 bool_t faux_rm(const char *path);
+bool_t faux_mkdir_p(const char *path, mode_t mode);
 char *faux_expand_tilde(const char *path);
 
 C_DECL_END

+ 1 - 0
faux/faux.map

@@ -104,6 +104,7 @@ FAUX_2.0 {
 		faux_isdir;
 		faux_isfile;
 		faux_rm;
+		faux_mkdir_p;
 		faux_expand_tilde;
 
 		faux_file_fdopen;