From: Youngjae Cho Date: Wed, 26 Jul 2023 05:34:11 +0000 (+0900) Subject: libcommon: Add syscommon_file_copy() X-Git-Tag: accepted/tizen/unified/20230731.175325~3 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=619e6c365399e371a1a2b7ad84ed7964e370e17f;p=platform%2Fcore%2Fsystem%2Flibsyscommon.git libcommon: Add syscommon_file_copy() Change-Id: I00608e8a28b61026e19c1e73d4e0ed063c50379f Signed-off-by: Youngjae Cho --- diff --git a/include/libsyscommon/file.h b/include/libsyscommon/file.h index 5c038e6..b879874 100644 --- a/include/libsyscommon/file.h +++ b/include/libsyscommon/file.h @@ -24,6 +24,7 @@ #define __LIBCOMMON_FILE_H__ #include +#include #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 diff --git a/src/libcommon/file.c b/src/libcommon/file.c index 6c6cbaf..c632ef5 100644 --- a/src/libcommon/file.c +++ b/src/libcommon/file.c @@ -31,6 +31,14 @@ #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; +}