added -D
[tridge/junkcode.git] / sendfile.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <sys/stat.h>
4 #include <fcntl.h>
5 #include <sys/sendfile.h>
6
7
8  int copy_file(const char *src, const char *dest)
9  {
10         int fd1, fd2;
11         int n;
12         struct stat sb;
13         off_t t;
14  
15         fd1 = open(src, O_RDONLY);
16         if (fd1 == -1) return -1;
17
18         unlink(dest);
19         fd2 = open(dest, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, 0666);
20         if (fd2 == -1) {
21                 close(fd1);
22                 return -1;
23         }
24  
25         fstat(fd1, &sb);
26         t = 0;
27         n = sendfile(fd2, fd1, &t, sb.st_size);
28         if (n != sb.st_size) {
29             close(fd2);
30             close(fd1);
31             unlink(dest);
32             return -1;
33         }
34  
35         close(fd1);
36
37         /* the close can fail on NFS if out of space */
38         if (close(fd2) == -1) {
39                 unlink(dest);
40                 return -1;
41         }
42
43         return 0;
44 }
45
46 int main(int argc, char *argv[])
47 {
48   return copy_file(argv[1], argv[2]);
49 }