diff --git a/pkg/fs/CMakeLists.txt b/pkg/fs/CMakeLists.txt index 293ea8d..1644907 100644 --- a/pkg/fs/CMakeLists.txt +++ b/pkg/fs/CMakeLists.txt @@ -1,5 +1,5 @@ add_library(onusfs) add_library(onus::fs ALIAS onusfs) -target_sources(onusfs PRIVATE src/tmp.c) +target_sources(onusfs PRIVATE src/tmp.c src/cpmv.c) target_include_directories(onusfs PUBLIC include) target_link_libraries(onusfs PUBLIC onus::common) \ No newline at end of file diff --git a/pkg/fs/src/cpmv.c b/pkg/fs/src/cpmv.c new file mode 100644 index 0000000..813df84 --- /dev/null +++ b/pkg/fs/src/cpmv.c @@ -0,0 +1,48 @@ +#define _XOPEN_SOURCE 2008 +#include +#include +#include +#include +#include +#include +#include "onus/err.h" +#include "onus/fs.h" + +/** + * Copies a file from one location to another, overwriting if necessary + * @param src: Path to original file + * @param dst: Path to destination file (including file name) + * @throws ONUS_E_FILE_NOT_FOUND if src does not point to an existing file, or + * if dst does not point to a path within an existing directory + * @throws ONUS_E_PERMISSION_ERROR if the user does not have permission to read + * src or to write to dst, ONUS_E_FS_ERR for unspecified file system errors + * @returns ONUS_SUCCESS on success + */ +int onus_fs_copy_file(const char *src, const char *dst) { + int fsrc = -1, fdst = -1; + struct stat srcstat; + off_t copied = 0; + int ret; + + fsrc = open(src, O_RDONLY); + fdst = open(dst, O_WRONLY | O_CREAT); + fstat(fsrc, &srcstat); + + if (!fsrc || !fdst) + return errno == EACCES ? ONUS_E_PERMISSION_ERROR : ONUS_E_FILE_NOT_FOUND; + + while (copied < srcstat.st_size) { + ssize_t c = sendfile(fdst, fsrc, &copied, SSIZE_MAX); + copied += c; + if (c == -1) { + ret = ONUS_E_FS_ERROR; + goto end; + } + }; + + ret = ONUS_SUCCESS; +end: + if (fsrc != -1) close(fsrc); + if (fdst != -1) close(fdst); + return ret; +} \ No newline at end of file diff --git a/pkg/fs/src/tmp.c b/pkg/fs/src/tmp.c index d1c3b8d..f717b74 100644 --- a/pkg/fs/src/tmp.c +++ b/pkg/fs/src/tmp.c @@ -1,13 +1,13 @@ #define _XOPEN_SOURCE 2008 -#include "onus/err.h" -#include "onus/fs.h" -#include "onus/str.h" #include #include #include #include #include #include +#include "onus/err.h" +#include "onus/fs.h" +#include "onus/str.h" /* TODO: Add def for windows */ static const char *kTemporaryDirectoryPathDefault = "/tmp";