summaryrefslogtreecommitdiff
path: root/slice.c
blob: 005084d7ee55820e879f906d26e22935681cca28 (plain)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
 * Extract a part from a file.
 *
 * Author: Peter Wu <lekensteyn@gmail.com>
 * Date: 2012-11-01
 */

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int main(int argc, char **argv) {
	char *filename;
	unsigned long seekpos, bytes_end;
	if (argc < 3) {
		fprintf(stderr, "Usage: %s file offset [last-exclusive-byte|+length]\n", *argv);
		return 1;
	}
	filename = argv[1];
	seekpos = strtoul(argv[2], NULL, 0);

	if (argc >= 4) {
		bytes_end = strtoul(argv[3], NULL, 0);
	} else {
		bytes_end = -1;
	}

	if (argc >= 4 && *argv[3] == '+') {
		if (bytes_end + seekpos < bytes_end) {
			fprintf(stderr, "Integer overflow on the last byte\n");
			return 1;
		}
		bytes_end += seekpos;
	}

	if (bytes_end < seekpos) {
		fprintf(stderr, "The last byte must be greater than the first byte.\n");
		return 1;
	}

	FILE *fp;
	if (filename[0] == '-' && filename[1] == 0)
		fp = stdin;
	else
		fp = fopen(filename, "r");
	if (!fp) {
		perror(filename);
		return 1;
	}

	unsigned long read_bytes = 0;
	if (!fseek(fp, seekpos, SEEK_SET))
		read_bytes += seekpos;

	do {
		char buf[8 * 1024];
		unsigned int read_count = sizeof(buf);
		unsigned long skip_bytes = 0;
		if (bytes_end - read_bytes < read_count)
			read_count = bytes_end - read_bytes;

		/* if fseek failed, discard some bytes */
		if (read_bytes < seekpos)
			skip_bytes = seekpos - read_bytes;

		unsigned long n = fread(buf, 1, read_count, fp);
		if (!n)
			break; /* EOF? */
		if (n > skip_bytes)
			write(STDOUT_FILENO, buf + skip_bytes, n);
		read_bytes += n;
	} while (read_bytes < bytes_end);

	if (bytes_end != -1UL && read_bytes != bytes_end)
		fprintf(stderr, "Output is truncated, missing %lu bytes.\n",
				bytes_end - read_bytes);

	fclose(fp);

	return 0;
}