libcommon: Add syscommon_file_copy() 55/296355/4
authorYoungjae Cho <y0.cho@samsung.com>
Wed, 26 Jul 2023 05:34:11 +0000 (14:34 +0900)
committerYoungjae Cho <y0.cho@samsung.com>
Thu, 27 Jul 2023 05:08:56 +0000 (14:08 +0900)
Change-Id: I00608e8a28b61026e19c1e73d4e0ed063c50379f
Signed-off-by: Youngjae Cho <y0.cho@samsung.com>
include/libsyscommon/file.h
src/libcommon/file.c

index 5c038e640e73a6b9be70804ab4c54ee55b3a1df4..b87987427c27f72876cf98feee3f0f1ba4909d61 100644 (file)
@@ -24,6 +24,7 @@
 #define __LIBCOMMON_FILE_H__
 
 #include <stdarg.h>
+#include <stdbool.h>
 
 #ifdef __cplusplus
 extern "C" {
@@ -101,6 +102,18 @@ int sys_set_str(char *fname, char *val);
  */
 int syscommon_parse_cmdline_scanf(const char *format, ...);
 
+/**
+ * @brief Copy file
+ *
+ * @param[in] src Absolute path for a source file
+ * @param[in] dst Absolute path for a destination
+ * @param[in] overwrite If true, overwrite destination file if exist.
+ *                      If false, return -EEXIST if there is destination file.
+ *
+ * @return zero on success, otherwise negative error value
+ */
+int syscommon_file_copy(const char *src, const char *dst, bool overwrite);
+
 #ifdef __cplusplus
 }
 #endif
index 6c6cbaf45bc31932635b3f492d7023ec172909fe..c632ef5e85210076bd5779d424eda4039f8d6672 100644 (file)
 
 #define SHARED_H_BUF_MAX 255
 
+static void close_fd(int *fd)
+{
+       if (*fd != -1)
+               close(*fd);
+}
+
+#define _cleanup_close_ __attribute__((__cleanup__(close_fd)))
+
 int sys_read_buf(char *file, char *buf, int len)
 {
        int fd, r;
@@ -164,3 +172,41 @@ int syscommon_parse_cmdline_scanf(const char *format, ...)
 
        return ret;
 }
+
+int syscommon_file_copy(const char *src, const char *dst, bool overwrite)
+{
+       _cleanup_close_ int rfd = -1;
+       _cleanup_close_ int wfd = -1;
+
+       char buf[1024] = { 0 ,};
+       ssize_t nread;
+       int r;
+
+       if (!src || !dst)
+               return -EINVAL;
+
+       if (!overwrite) {
+               r = access(dst, F_OK);
+               if (r == 0)
+                       return -EALREADY;
+               else if (errno != ENOENT)
+                       return -errno;
+       }
+
+       wfd = open(dst, O_CREAT | O_WRONLY | O_TRUNC, 0644);
+       if (wfd < 0)
+               return -errno;
+
+       rfd = open(src, O_RDONLY);
+       if (rfd < 0)
+               return -errno;
+
+       while ((nread = read(rfd, buf, 1024)) > 0)
+               if (write(wfd, buf, nread) != nread)
+                       return -errno;
+
+       if (nread < 0)
+               return -errno;
+
+       return 0;
+}