/* sendfilecp.c - copying a file using sendfile */ #include #include #include #include #include #include #include #include #include extern int errno; int main (int argc, char* argv[]) { /* check that we have the right number of command line parameters */ if (argc != 3) { fprintf(stderr, "usage: %s \n", argv[0]); exit(1); } int fdin; /* file descriptor of source file */ int fdout; /* file descriptor of destination file */ struct stat statbuf; /* metadata for source file */ int offset = 0; /* byte offset used by sendfile */ int rc; /* return code from sendfile */ /* Open source file */ fdin = open(argv[1], O_RDONLY); if (fdin == -1) { fprintf(stderr, "unable to open %s - %s\n", argv[1], strerror(errno)); exit(1); } /* open destination file */ fdout = open(argv[2], O_WRONLY|O_CREAT, statbuf.st_mode); if (fdout == -1) { fprintf(stderr, "unable to open %s -%s\n", argv[2], strerror(errno)); exit(1); } /* get metadata of the source file */ if (fstat(fdin, &statbuf) == -1) { fprintf(stderr, "unable to obtain metadata for %s - %s\n", argv[1], strerror(errno)); exit(1); } /* copy file */ rc = sendfile (fdout, fdin, (off_t *)&offset, statbuf.st_size); if (rc == -1) { fprintf(stderr, "sendfile error - %s\n", strerror(errno)); exit(1); } if (rc != statbuf.st_size) { fprintf(stderr, "sendfile error - partial transfer: %d of %d bytes\n", rc, (int)statbuf.st_size); exit(1); } /* clean up and exit */ close(fdout); close(fdin); return 0; }