-
+ DCA3567C27D22156D45BDBB018961469EC4CA2AF26ED7EFA3D060CC237088F1B3FB8BB2DF50B627B8F0F24C1D1D7CD56F497D0F9F5A1330B8549C15D5AC76910
io.c
(0 . 0)(1 . 75)
50 /* Minimalist POSIX I/O (unbuffered, dies on error)
51 * J. Welsh, May 2019
52 */
53
54 #include <errno.h>
55 #include <signal.h>
56 #include <string.h>
57 #include <unistd.h>
58 #include "io.h"
59
60 void write_all(int fd, char const *buf, size_t len) {
61 while (len) {
62 ssize_t n = write(fd,buf,len);
63 if (n < 0) {
64 if (errno == EINTR) continue;
65 if (fd != 2) /* prevent loop */
66 perr("write_all");
67 _exit(errno);
68 }
69 buf += n;
70 len -= n;
71 }
72 }
73
74 size_t read_all(int fd, unsigned char *buf, size_t len) {
75 size_t olen = len;
76 while (len) {
77 ssize_t n = read(fd,buf,len);
78 if (n <= 0) {
79 if (n) {
80 if (errno == EINTR) continue;
81 perr("read_all");
82 _exit(errno);
83 }
84 break;
85 }
86 buf += n;
87 len -= n;
88 }
89 return olen - len;
90 }
91
92 void write_str(int fd, char const *s) {
93 write_all(fd,s,strlen(s));
94 }
95
96 void newline(int fd) {
97 write_all(fd,"\n",1);
98 }
99
100 void write_line(int fd, char const *s) {
101 write_str(fd,s);
102 newline(fd);
103 }
104
105 void assert_fail(char const *expr) {
106 write_str(2,"Assertion failed: ");
107 write_line(2,expr);
108 raise(SIGABRT);
109 _exit(1);
110 }
111
112 void perr(char const *context) {
113 write_str(2,context);
114 write_str(2,": ");
115 write_line(2,strerror(errno));
116 }
117
118 int chkp(char const *context, int ret) {
119 if (ret == -1) {
120 perr(context);
121 _exit(errno);
122 }
123 return ret;
124 }