1 #include "cache.h"
3 int read_in_full(int fd, void *buf, size_t count)
4 {
5 char *p = buf;
6 ssize_t total = 0;
7 ssize_t loaded = 0;
9 while (count > 0) {
10 loaded = xread(fd, p, count);
11 if (loaded <= 0) {
12 if (total)
13 return total;
14 else
15 return loaded;
16 }
17 count -= loaded;
18 p += loaded;
19 total += loaded;
20 }
22 return total;
23 }
25 void read_or_die(int fd, void *buf, size_t count)
26 {
27 ssize_t loaded;
29 loaded = read_in_full(fd, buf, count);
30 if (loaded == 0)
31 die("unexpected end of file");
32 else if (loaded < 0)
33 die("read error (%s)", strerror(errno));
34 }
36 int write_in_full(int fd, const void *buf, size_t count)
37 {
38 const char *p = buf;
39 ssize_t total = 0;
40 ssize_t written = 0;
42 while (count > 0) {
43 written = xwrite(fd, p, count);
44 if (written <= 0) {
45 if (total)
46 return total;
47 else
48 return written;
49 }
50 count -= written;
51 p += written;
52 total += written;
53 }
55 return total;
56 }
58 void write_or_die(int fd, const void *buf, size_t count)
59 {
60 ssize_t written;
62 written = write_in_full(fd, buf, count);
63 if (written == 0)
64 die("disk full?");
65 else if (written < 0) {
66 if (errno == EPIPE)
67 exit(0);
68 die("write error (%s)", strerror(errno));
69 }
70 }
72 int write_or_whine_pipe(int fd, const void *buf, size_t count, const char *msg)
73 {
74 ssize_t written;
76 written = write_in_full(fd, buf, count);
77 if (written == 0) {
78 fprintf(stderr, "%s: disk full?\n", msg);
79 return 0;
80 }
81 else if (written < 0) {
82 if (errno == EPIPE)
83 exit(0);
84 fprintf(stderr, "%s: write error (%s)\n",
85 msg, strerror(errno));
86 return 0;
87 }
89 return 1;
90 }
92 int write_or_whine(int fd, const void *buf, size_t count, const char *msg)
93 {
94 ssize_t written;
96 written = write_in_full(fd, buf, count);
97 if (written == 0) {
98 fprintf(stderr, "%s: disk full?\n", msg);
99 return 0;
100 }
101 else if (written < 0) {
102 fprintf(stderr, "%s: write error (%s)\n",
103 msg, strerror(errno));
104 return 0;
105 }
107 return 1;
108 }