/* * textio: read/write routines for text. These can be used in programs * where read and write are used instead of the (preferred) stdio routines * for manipulating text files, by doing something like * #define read _text_read * Written by Eric R. Smith and placed in the public domain. */ #include #include int _text_read(fd, buf, nbytes) int fd; char *buf; int nbytes; { char *to, *from; int r; _again: r = read(fd, buf, nbytes); if (r <= 0) return r; nbytes = r; to = from = buf; while (r-- > 0) { if (*from == '\r') { from++; nbytes--; } else *to++ = *from++; } if (nbytes == 0) goto _again; return nbytes; } int _text_write(fd, from, nbytes) int fd; char *from; int nbytes; { char buf[BUFSIZ+2], *to, c; int w, r, bytes_written; bytes_written = 0; while (bytes_written < nbytes) { w = 0; to = buf; while (w < BUFSIZ && bytes_written < nbytes) { if ((c = *from++) == '\n') { *to++ = '\r'; *to++ = c; w += 2; } else { *to++ = c; w++; } bytes_written++; } if ((r = write(fd, buf, w)) != w) return (r < 0) ? r : bytes_written - (w-r); } return bytes_written; }