diff --git a/inc/files.h b/inc/files.h index 2a6a518..2431a6f 100644 --- a/inc/files.h +++ b/inc/files.h @@ -33,4 +33,7 @@ bool scan(const std::string& path, fileCallback clb, bool prefixdir = false, fil bool readFile(const std::string& name, std::ostream& output, unsigned int maxsize = 0); //reads file name and writes it line for line into output, it stops at maxsize (it might be a bit more, its not a hard limit - see it more as a hint), if maxsize is 0 it reads unlimited bool readFile(int fd, std::ostream& output, unsigned int maxsize = 0); +bool copy(int fd_from, int fd_to); +bool copy(const std::string& from, const std::string& to); + } \ No newline at end of file diff --git a/src/files.cpp b/src/files.cpp index ab2b02c..7364e2f 100644 --- a/src/files.cpp +++ b/src/files.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include "util.h" @@ -108,3 +109,39 @@ bool mrbesen::files::readFile(int fd, std::ostream& output, unsigned int maxsize return true; } +bool mrbesen::files::copy(int fd_from, int fd_to) { + static const uint32_t BUFFERSIZE = 4096; + char buf[BUFFERSIZE]; + ssize_t rc = -1; + while(rc) { + rc = read(fd_from, buf, BUFFERSIZE); + if(rc < 0) return false; //reading error + if(rc > 0) { + ssize_t wc = write(fd_to, buf, rc); + if(wc != rc) return false; //writing error + } + } + + return true; +} + +bool mrbesen::files::copy(const std::string& from, const std::string& to) { + int fd1 = open(from.c_str(), O_RDONLY); + if(fd1 < 0) return false; + + struct stat sb; + if(fstat(fd1, &sb)) { + close(fd1); + return false; + } + int fd2 = open(to.c_str(), O_WRONLY | O_CREAT, sb.st_mode); + + bool r = false; + if(fd2 > -1) + r = copy(fd1, fd2); + + close(fd1); + close(fd2); + + return r; +}