[PATCH] Use error() throughout examples
[splice.git] / splice-cp.c
CommitLineData
d8525fbd
JA
1/*
2 * Splice cp a file
3 */
4#include <stdio.h>
5#include <stdlib.h>
6#include <unistd.h>
7#include <fcntl.h>
8#include <errno.h>
9#include <sys/types.h>
10#include <sys/stat.h>
11
12#include "splice.h"
13
14#define BS SPLICE_SIZE
15
16int main(int argc, char *argv[])
17{
18 int in_fd, out_fd, pfds[2];
19 struct stat sb;
20
21 if (argc < 3) {
22 printf("%s: infile outfile\n", argv[0]);
23 return 1;
24 }
25
26 in_fd = open(argv[1], O_RDONLY);
49b68ef7
JA
27 if (in_fd < 0)
28 return error("open input");
d8525fbd 29
49b68ef7
JA
30 if (fstat(in_fd, &sb) < 0)
31 return error("stat input");
d8525fbd
JA
32
33 out_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
49b68ef7
JA
34 if (out_fd < 0)
35 return error("open output");
d8525fbd 36
49b68ef7
JA
37 if (pipe(pfds) < 0)
38 return error("pipe");
d8525fbd
JA
39
40 do {
49b68ef7 41 int this_len = min((off_t) BS, sb.st_size);
d8525fbd
JA
42 int ret = splice(in_fd, NULL, pfds[1], NULL, this_len, SPLICE_F_NONBLOCK);
43
44 if (ret <= 0)
45 return error("splice-in");
46
47 sb.st_size -= ret;
48 while (ret > 0) {
49 int written = splice(pfds[0], NULL, out_fd, NULL, ret, 0);
50 if (written <= 0)
51 return error("splice-out");
52 ret -= written;
53 }
54 } while (sb.st_size);
55
56 close(in_fd);
57 close(pfds[1]);
58 close(out_fd);
59 close(pfds[0]);
60 return 0;
61}