Code

I like the idea of the new ':/<oneline prefix>' notation, and gave it
[git.git] / write_or_die.c
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;
8         while (count > 0) {
9                 ssize_t loaded = xread(fd, p, count);
10                 if (loaded <= 0)
11                         return total ? total : loaded;
12                 count -= loaded;
13                 p += loaded;
14                 total += loaded;
15         }
17         return total;
18 }
20 int write_in_full(int fd, const void *buf, size_t count)
21 {
22         const char *p = buf;
23         ssize_t total = 0;
25         while (count > 0) {
26                 ssize_t written = xwrite(fd, p, count);
27                 if (written < 0)
28                         return -1;
29                 if (!written) {
30                         errno = ENOSPC;
31                         return -1;
32                 }
33                 count -= written;
34                 p += written;
35                 total += written;
36         }
38         return total;
39 }
41 void write_or_die(int fd, const void *buf, size_t count)
42 {
43         if (write_in_full(fd, buf, count) < 0) {
44                 if (errno == EPIPE)
45                         exit(0);
46                 die("write error (%s)", strerror(errno));
47         }
48 }
50 int write_or_whine_pipe(int fd, const void *buf, size_t count, const char *msg)
51 {
52         if (write_in_full(fd, buf, count) < 0) {
53                 if (errno == EPIPE)
54                         exit(0);
55                 fprintf(stderr, "%s: write error (%s)\n",
56                         msg, strerror(errno));
57                 return 0;
58         }
60         return 1;
61 }
63 int write_or_whine(int fd, const void *buf, size_t count, const char *msg)
64 {
65         if (write_in_full(fd, buf, count) < 0) {
66                 fprintf(stderr, "%s: write error (%s)\n",
67                         msg, strerror(errno));
68                 return 0;
69         }
71         return 1;
72 }