summaryrefslogtreecommitdiffstats
path: root/splice.c
blob: 2f11291569b7536381ba92fa639d5259d40bd718 (plain) (blame)
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
59
60
#include <err.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

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) {
		printf("USAGE: fwpatch 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 length");
	} else {
		end = -1;
	}

	pos = 0;
	while (!feof(main_file) || !feof(stdin)) {
		if (pos >= start && !feof(stdin)) {
			nread = fread(buf, 1, BUFSIZ, stdin);
			if (pos == start && end >= 0)
				fseek(main_file, end, SEEK_CUR);
			else if (end < 0)
				fseek(main_file, nread, SEEK_CUR);
		} else {
			if (start > pos) {
				nreq = start - pos;
				if (nreq > BUFSIZ)
					nreq = BUFSIZ;
			} else {
				nreq = BUFSIZ;
			}
			nread = fread(buf, 1, nreq, main_file);
		}
		if (fwrite(buf, 1, nread, stdout) != nread)
			errx(1, "output truncated");
		pos += nread;
	}

	fclose(main_file);
}