From 927c684fc2c747f724d0a149b8c7c172cdf562b0 Mon Sep 17 00:00:00 2001 From: Celine Mercier Date: Thu, 3 Aug 2017 16:28:54 +0200 Subject: [PATCH] Utils: new function to copy the content of a file into another file --- src/utils.c | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/utils.h | 14 +++++++++++++ 2 files changed, 74 insertions(+) diff --git a/src/utils.c b/src/utils.c index 606f154..564e2d8 100644 --- a/src/utils.c +++ b/src/utils.c @@ -36,6 +36,66 @@ **********************************************************************/ +int copy_file(const char* src_file_path, const char* dest_file_path) +{ + int src_fd, dst_fd, n, err; + unsigned char buffer[4096]; + + src_fd = open(src_file_path, O_RDONLY); + if (src_fd == -1) + { + obi_set_errno(OBI_UTILS_ERROR); + obidebug(1, "\nError opening a file to copy"); + return -1; + } + dst_fd = open(dest_file_path, O_CREAT | O_WRONLY, 0777); // overwrite if already exists + if (dst_fd == -1) + { + obi_set_errno(OBI_UTILS_ERROR); + obidebug(1, "\nError opening a file to write a copy: %s", dest_file_path); + return -1; + } + + while (1) + { + err = read(src_fd, buffer, 4096); + if (err == -1) + { + obi_set_errno(OBI_UTILS_ERROR); + obidebug(1, "\nProblem reading a file to copy"); + return -1; + } + n = err; + + if (n == 0) + break; + + err = write(dst_fd, buffer, n); + if (err == -1) + { + obi_set_errno(OBI_UTILS_ERROR); + obidebug(1, "\nProblem writing to a file while copying"); + return -1; + } + } + + if (close(src_fd) < 0) + { + obi_set_errno(OBI_UTILS_ERROR); + obidebug(1, "\nError closing a file after copying it"); + return -1; + } + if (close(dst_fd) < 0) + { + obi_set_errno(OBI_UTILS_ERROR); + obidebug(1, "\nError closing a file after copying to it"); + return -1; + } + + return 0; +} + + int digit_count(index_t i) { int n_digits; diff --git a/src/utils.h b/src/utils.h index 752747d..f0b8d69 100644 --- a/src/utils.h +++ b/src/utils.h @@ -25,6 +25,20 @@ #define ONE_IF_ZERO(x) (((x)==0)?1:(x)) /**< If x is equal to 0, x takes the value 1. */ +/** + * @brief Copy the content of a file into another file. + * + * @param src_file_path The path to the source file to copy. + * @param dest_file_path The path to the destination file. + * + * @retval 0 if the operation was successfully completed. + * @retval -1 if an error occurred. + * + * @since July 2017 + * @author Celine Mercier (celine.mercier@metabarcoding.org) + */ +int copy_file(const char* src_file_path, const char* dest_file_path); + /** * @brief Counts the number of digits of a number.