#include #include #include #define BUFSIZE 512 /* size of chunk to be read */ #define PERM 0644 /* file permission of new file */ int copyfile(const char *name1, const char *name2); int main(argc, argv) int argc; char *argv[]; { if (argc < 3) { printf("Usage: mycp \n\n"); return -1; } // end if argc < 3 if (copyfile(argv[1], argv[2]) == 0) return 0; else return -1; } int copyfile(const char *name1, const char *name2) { int infile, outfile; ssize_t nread; char buffer[BUFSIZE]; if ((infile = open(name1, O_RDONLY)) == -1) { perror("Error opening file1: %s", name1); return -1; } if ((outfile = open(name2, O_WRONLY | O_CREAT | O_TRUNC, PERM)) == -1) { close(infile); perror("Error opening file2: %s", name2); return -2; } while ((nread = read(infile, buffer, BUFSIZE)) > 0) { if (write(outfile, buffer, nread) < nread) { close(infile); close(outfile); perror("Error writing to file2"); return -3; } // end if } // end while close(infile); close(outfile); return 0; }