// translated from copy.c page 71 of the book. #include #include #include #include #include #include #include using namespace std; const size_t BUF_SIZE{1024}; int main(int argc, char * argv[]) { int inputFd{-1}, outputFd{-1}, openFlags{O_CREAT | O_WRONLY | O_TRUNC}; mode_t filePerms{S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH}; int numRead; char buf[BUF_SIZE]; // warning, danger Will Robinson string errorMsg; if (argc != 3 or strcmp(argv[1],"--help") == 0) { cerr << "Usage: " << argv[0] << " infile outfile " << endl; } inputFd = open(argv[1], O_RDONLY); if (inputFd == -1) { errorMsg = argv[1]; // apparently string + char * is not implemented. //errorMsg = " open failed for " + argv[1]; errorMsg = " open failed for " + errorMsg; perror(errorMsg.c_str()); return 1; } outputFd = open(argv[2], openFlags, filePerms); if (outputFd == -1) { errorMsg = argv[2]; errorMsg = " open failed for " + errorMsg; perror(errorMsg.c_str()); return 1; } while((numRead = read(inputFd, buf, BUF_SIZE)) > 0) { if (write(outputFd, buf, numRead) != numRead) { perror("could not write the entire output buffer"); return 1; } } if (close(inputFd) == -1) { errorMsg = argv[1]; errorMsg = " failed to close " + errorMsg; perror(errorMsg.c_str()); return 1; } if (close(outputFd) == -1) { errorMsg = argv[2]; errorMsg = " failed to close " + errorMsg; perror(errorMsg.c_str()); return 1; } return 0; }