summaryrefslogtreecommitdiffstats
path: root/splice.c
diff options
context:
space:
mode:
Diffstat (limited to 'splice.c')
-rw-r--r--splice.c22
1 files changed, 10 insertions, 12 deletions
diff --git a/splice.c b/splice.c
index 2f11291..0fe63c6 100644
--- a/splice.c
+++ b/splice.c
@@ -3,6 +3,8 @@
#include <stdint.h>
#include <stdlib.h>
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
+
int
main(int argc, const char **argv)
{
@@ -14,7 +16,7 @@ main(int argc, const char **argv)
int ret;
if (argc < 3 || argc > 4) {
- printf("USAGE: fwpatch MAIN START [END]\n");
+ fprintf(stderr, "USAGE: splice MAIN START [END]\n");
return 0;
}
@@ -28,27 +30,23 @@ main(int argc, const char **argv)
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");
+ if (start >= end) errx(1, "invalid end");
} 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 && (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_CUR);
+ fseek(main_file, end, SEEK_SET);
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;
- }
+ nreq = pos < start ? MIN(BUFSIZ, start - pos) : BUFSIZ;
nread = fread(buf, 1, nreq, main_file);
}
if (fwrite(buf, 1, nread, stdout) != nread)