/* * copy-file-syscalls.c * * usage: ./copy-file source-file destination-file */ #include #include #include #include #include #include #define BYTES_PER_ITERATION 10240 int main(int argc, char *argv[]) { int src_fd, dst_fd; char *src_filename, *dst_filename; int n; char buf[BYTES_PER_ITERATION]; /* check command-line args */ if(argc != 3) { printf("usage: %s src_filename dst_filename\n", argv[0]); exit(1); } src_filename = argv[1]; dst_filename = argv[2]; /* open files */ if((src_fd = open(src_filename, O_RDONLY)) < 0) { perror("open"); exit(2); } if((dst_fd = open(dst_filename, O_CREAT | O_WRONLY, 0666)) < 0) { perror("open"); exit(3); } /* do the copy */ while((n = read(src_fd, buf, BYTES_PER_ITERATION)) > 0) { n = write(dst_fd, buf, n); if(n < 0) { perror("write"); exit(4); } } /* according to the read(2) manpage, it returns 0 on EOF and negative on * error */ if(n < 0) { perror("read"); exit(5); } /* clean up */ close(src_fd); close(dst_fd); }