1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
#include <err.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define MIN(a, b) ((a) < (b) ? (a) : (b))
int
main(int argc, const char **argv)
{
char buf[BUFSIZ];
ssize_t start, end;
ssize_t pos, nread, nreq;
FILE *main_file;
char *endc;
int ret;
if (argc < 3 || argc > 4) {
fprintf(stderr, "USAGE: splice MAIN START [END]\n");
return 0;
}
main_file = fopen(argv[1], "rb");
if (!main_file) err(1, "fopen %s", argv[1]);
start = strtoll(argv[2], &endc, 0);
if (endc && *endc) err(1, "strtoll %s", argv[2]);
if (start < 0) errx(1, "negative start");
if (argc == 4) {
end = strtoll(argv[3], &endc, 0);
if (endc && *endc) err(1, "strtoll %s", argv[3]);
if (start >= end) errx(1, "invalid end");
} else {
end = -1;
}
pos = 0;
while (!feof(main_file) || !feof(stdin)) {
if (pos >= start && (pos < end || !feof(stdin))) {
if (feof(stdin)) errx(1, "input truncated");
nreq = end >= 0 ? MIN(BUFSIZ, end - start) : BUFSIZ;
nread = fread(buf, 1, nreq, stdin);
if (pos == start && end >= 0)
fseek(main_file, end, SEEK_SET);
else if (end < 0)
fseek(main_file, nread, SEEK_CUR);
} else {
nreq = pos < start ? MIN(BUFSIZ, start - pos) : BUFSIZ;
nread = fread(buf, 1, nreq, main_file);
}
if (fwrite(buf, 1, nread, stdout) != nread)
errx(1, "output truncated");
pos += nread;
}
fclose(main_file);
}
|