aboutsummaryrefslogtreecommitdiffstats
path: root/common.c
blob: e1d4e03ca02a73704c1823e264aeb04b9c30b640 (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
/* See LICENSE file for copyright and license details. */
#include "common.h"


void
copy_file(int destfd, const char *destfname, int srcfd, const char *srcfname, int *okp)
{
	char buf[BUFSIZ];
	ssize_t r, w, p, ok_off;
	size_t read_off;

	if (okp) {
		*okp = 0;
		ok_off = 1;
		read_off = 0;
	} else {
		ok_off = 0;
		read_off = 1;
		buf[0] = 0;
	}

	for (;;) {
		r = read(srcfd, &buf[read_off], sizeof(buf) - read_off);
		if (r <= 0) {
			if (!r)
				break;
			fprintf(stderr, "%s: read %s: %s\n", argv0, srcfname, strerror(errno));
			exit(1);
		}

		if (r == ok_off) { /* Only possible if okp != NULL */
			*okp = 1;
			break;
		}

		r += (ssize_t)read_off;
		for (p = ok_off; p < r; p += w) {
			w = write(destfd, &buf[p], (size_t)(r - p));
			if (w <= 0) {
				fprintf(stderr, "%s: write %s: %s\n", argv0, destfname, strerror(errno));
				exit(1);
			}
		}
	}

	if (!okp) {
		w = write(destfd, buf, 1);
		if (w <= 0) {
			fprintf(stderr, "%s: write %s: %s\n", argv0, destfname, strerror(errno));
			exit(1);
		}
	}
}