/* *--------------------------------------------------------------------- * copyExample.cpp - demonstrate use of Linux System API to copy files * * Jim Fawcett, Summer ShortCourse, Summer 2016 *--------------------------------------------------------------------- */ #include /* * The man pages say the following two headers are needed for open(). * Apparently unistd.h includes them indirectly */ //#include // apparently unistd.h includes this //#include // apparently unistd.h includes this #include // permissions #include // universal device IO using namespace std; void openErr(const char* filename) { std::cout << "\n error opening file \"" << filename << "\"\n\n"; exit(1); } void opened(const char* filename) { std::cout << "\n opening file \"" << filename; } void exitError(const char* error) { std::cout << "\n " << error << "\n\n"; exit(1); } /* * ----< demonstrate use of device IO >------------------------------ */ #define BUF_SIZE 512 int main(int argc, char** argv) { if(argc < 2) { std::cout << "\n please enter src and destination filenames\n\n"; return 1; } /* open input file */ int inFd = open(argv[1], O_RDONLY); if(inFd == -1) openErr(argv[1]); else opened(argv[1]); /* open output file */ int openFlags = O_CREAT | O_WRONLY | O_TRUNC; mode_t filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; int outFd = open(argv[2], openFlags, filePerms); if(outFd == -1) openErr(argv[2]); else opened(argv[2]); /* copy in to out */ char buf[BUF_SIZE]; size_t numRead; size_t count = 0; while((numRead = read(inFd, buf, BUF_SIZE)) > 0) { if(write(outFd, buf, numRead) != numRead) exitError("couldn't write entire buffer"); std::cout << "\n copying block #" << ++count << " of size " << numRead; } if(numRead == -1) exitError("read error"); /* show that file sizes match */ off_t inSize = lseek(inFd, 0, SEEK_END); off_t outSize = lseek(outFd, 0, SEEK_END); std::cout << "\n size of source " << argv[1] << " = " << inSize; std::cout << "\n size of destin " << argv[2] << " = " << outSize; /* clean up */ close(inFd); close(outFd); std::cout << "\n\n"; return 0; }