misc.c (1064B)
1 #include <sys/types.h> 2 3 #include <stdarg.h> 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <unistd.h> 7 8 #define NERRBUF 128 9 static char errbuf[NERRBUF]; 10 11 ssize_t 12 xread(int fd, void *buf, size_t nbytes) 13 { 14 unsigned char *bp = buf; 15 ssize_t total = 0; 16 17 while (nbytes > 0) { 18 ssize_t n; 19 20 n = read(fd, &bp[total], nbytes); 21 if (n < 0) 22 return -1; 23 else if (n == 0) 24 return total; 25 total += n; 26 nbytes -= n; 27 } 28 return total; 29 } 30 31 ssize_t 32 xwrite(int fd, void *buf, size_t nbytes) 33 { 34 unsigned char *bp = buf; 35 ssize_t total = 0; 36 37 while (nbytes > 0) { 38 ssize_t n; 39 40 n = write(fd, &bp[total], nbytes); 41 if (n < 0) 42 return -1; 43 else if (n == 0) 44 return total; 45 total += n; 46 nbytes -= n; 47 } 48 return total; 49 } 50 51 void 52 seterr(char *fmt, ...) 53 { 54 va_list ap; 55 56 va_start(ap, fmt); 57 vsnprintf(errbuf, NERRBUF, fmt, ap); 58 va_end(ap); 59 } 60 61 void 62 printerr(char *fmt, ...) 63 { 64 va_list ap; 65 66 va_start(ap, fmt); 67 vfprintf(stderr, fmt, ap); 68 if (errbuf[0] == '\0') 69 fprintf(stderr, ": unknown error\n"); 70 else 71 fprintf(stderr, ": %s\n", errbuf); 72 va_end(ap); 73 exit(1); 74 }