libcommon: Add syscommon_mkdir() 70/296370/5
authorYoungjae Cho <y0.cho@samsung.com>
Wed, 26 Jul 2023 07:34:36 +0000 (16:34 +0900)
committerYoungjae Cho <y0.cho@samsung.com>
Thu, 27 Jul 2023 05:08:56 +0000 (14:08 +0900)
 It makes directory of the given path, including the whole intermediate
path if not exists. That is, it is equivalent to command 'mkdir -p'.
 It has come from the deviced as the function is eligible to being a
common function to be utilized by overall system libs/daemons.

Change-Id: Ifbf23c3fe721a149c54d6f650cce093dfb6f9e10
Signed-off-by: Youngjae Cho <y0.cho@samsung.com>
include/libsyscommon/common.h
src/libcommon/common.c

index f6cd1081098e28e83929eccb518d01ce14508e96..14d20deec93a28d8a7d1f22d504d59f644779e76 100644 (file)
@@ -24,6 +24,7 @@
 #define __SYSCOMMON_COMMON_H__
 
 #include <stdbool.h>
+#include <sys/types.h>
 
 #ifdef __cplusplus
 extern "C" {
@@ -50,6 +51,13 @@ bool syscommon_is_container(void);
  */
 bool syscommon_is_mounted(const char *path);
 
+/**
+ * @brief Make directory including intermediate directories
+ *
+ * @return 0 on succes, otherwise negative error value
+ */
+int syscommon_mkdir(const char *path, mode_t mode);
+
 #ifdef __cplusplus
 }
 #endif
index 0a220c7678331540ed76ed43648eb8af4e3d6367..116c131e7a6cdc790d47bf577a98b7965d9ba1a3 100644 (file)
@@ -25,6 +25,7 @@
 #include <stdlib.h>
 #include <unistd.h>
 #include <mntent.h>
+#include <sys/stat.h>
 #include <system_info.h>
 #include "shared/log.h"
 #include "libsyscommon/common.h"
@@ -33,6 +34,8 @@
 #define FEATURE_MODEL_NAME_EMULATOR   "Emulator"
 #define CONTAINER_FILE_PATH           "/run/systemd/container"
 
+#define PATH_MAX       256
+
 bool syscommon_is_emulator(void)
 {
        int ret = 0;
@@ -99,3 +102,32 @@ bool syscommon_is_mounted(const char *path)
        endmntent(fp);
        return ret;
 }
+
+int syscommon_mkdir(const char *path, mode_t mode)
+{
+       char dir[PATH_MAX] = { 0, };
+       size_t sep, l;
+       int pos;
+       int ret;
+
+       if (!path)
+               return -EINVAL;
+
+       l = strlen(path);
+
+       for (pos = 0, sep = 0; pos < l; pos += sep + 1) {
+               sep = strcspn(path + pos, "/");
+               if (!sep)
+                       continue;
+
+               ret = snprintf(dir, pos + sep + 1, "%s", path);
+               if (ret < 0)
+                       return ret;
+
+               ret = mkdir(dir, mode);
+               if (ret < 0 && errno != EEXIST)
+                       return -errno;
+       }
+
+       return 0;
+}