b388b86b3b56cb4781c5b5e42caaf42dba9f15aa
[splice.git] / splice-out.c
1 /*
2  * Splice stdin to file
3  */
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7 #include <fcntl.h>
8 #include <sys/stat.h>
9
10 #include "splice.h"
11
12 static int splice_flags;
13
14 static int usage(char *name)
15 {
16         fprintf(stderr, "... | %s: [-m] out_file\n", name);
17         return 1;
18 }
19
20 static int parse_options(int argc, char *argv[])
21 {
22         int c, index = 1;
23
24         while ((c = getopt(argc, argv, "m")) != -1) {
25                 switch (c) {
26                 case 'm':
27                         splice_flags = SPLICE_F_MOVE;
28                         index++;
29                         break;
30                 default:
31                         return -1;
32                 }
33         }
34
35         return index;
36 }
37
38 int main(int argc, char *argv[])
39 {
40         struct stat sb;
41         int fd, index;
42
43         if (fstat(STDIN_FILENO, &sb) < 0)
44                 return error("stat");
45         if (!S_ISFIFO(sb.st_mode)) {
46                 fprintf(stderr, "stdin must be a pipe\n");
47                 return usage(argv[0]);
48         }
49
50         index = parse_options(argc, argv);
51         if (index == -1 || index + 1 > argc)
52                 return usage(argv[0]);
53
54         fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
55         if (fd < 0)
56                 return error("open");
57
58         do {
59                 int ret = splice(STDIN_FILENO, NULL, fd, NULL, SPLICE_SIZE, splice_flags);
60
61                 if (ret < 0)
62                         return error("splice");
63                 else if (!ret)
64                         break;
65         } while (1);
66
67         close(fd);
68         return 0;
69 }