From 53d2395dc15030ab9df5bb8b5f315bd7e7c2f849 Mon Sep 17 00:00:00 2001 Message-Id: <53d2395dc15030ab9df5bb8b5f315bd7e7c2f849.1746225740.git.mdw@distorted.org.uk> From: Mark Wooding Date: Fri, 13 Sep 2024 21:54:57 +0100 Subject: [PATCH] lib.c (dstr_readline): Rewrite to cope with embedded zero bytes. Organization: Straylight/Edgeware From: Mark Wooding Alas, `fgets' produces nonsense when there are zero bytes, so we have to do this by hand. --- lib.c | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/lib.c b/lib.c index 99cad5d..f0fb6e2 100644 --- a/lib.c +++ b/lib.c @@ -232,19 +232,21 @@ PRINTF_LIKE(2, 3) void dstr_putf(struct dstr *d, const char *p, ...) */ int dstr_readline(struct dstr *d, FILE *fp) { + char *p = d->p + d->len, *lim = d->p + d->sz; size_t n; - int any = 0; + int ch; + ch = getc(fp); if (ch == EOF) return (-1); for (;;) { - dstr_ensure(d, 2); - if (!fgets(d->p + d->len, d->sz - d->len, fp)) break; - n = strlen(d->p + d->len); assert(n > 0); any = 1; - d->len += n; - if (d->p[d->len - 1] == '\n') { d->p[--d->len] = 0; break; } + if (p == lim) { + n = d->len = p - d->p; dstr_ensure(d, 1); + p = d->p + n; lim = d->p + d->sz; + } + if (ch == EOF || ch == '\n') break; + *p++ = ch; ch = getc(fp); } - - if (!any) return (-1); - else return (0); + d->len = p - d->p; *p++ = 0; + return (0); } /*----- Dynamic vectors of strings ----------------------------------------*/ -- [mdw]