X-Git-Url: http://nsz.repo.hu/git/?a=blobdiff_plain;f=src%2Fstdio%2Ffgets.c;h=6171f398dacb4170a5a1227d515788d5457b252e;hb=0847902ab99065a48f9bd3729b6e676288dfd69e;hp=b01a4187037d81e6457e473c4e682e24787c9021;hpb=835f9f950e2f6059532bd9ab9857a856ed21a4fd;p=musl diff --git a/src/stdio/fgets.c b/src/stdio/fgets.c index b01a4187..6171f398 100644 --- a/src/stdio/fgets.c +++ b/src/stdio/fgets.c @@ -10,23 +10,27 @@ char *fgets(char *restrict s, int n, FILE *restrict f) size_t k; int c; + FLOCK(f); + if (n--<=1) { + f->mode |= f->mode-1; + FUNLOCK(f); if (n) return 0; *s = 0; return s; } - FLOCK(f); - while (n) { - z = memchr(f->rpos, '\n', f->rend - f->rpos); - k = z ? z - f->rpos + 1 : f->rend - f->rpos; - k = MIN(k, n); - memcpy(p, f->rpos, k); - f->rpos += k; - p += k; - n -= k; - if (z || !n) break; + if (f->rpos != f->rend) { + z = memchr(f->rpos, '\n', f->rend - f->rpos); + k = z ? z - f->rpos + 1 : f->rend - f->rpos; + k = MIN(k, n); + memcpy(p, f->rpos, k); + f->rpos += k; + p += k; + n -= k; + if (z || !n) break; + } if ((c = getc_unlocked(f)) < 0) { if (p==s || !feof(f)) s = 0; break; @@ -34,7 +38,7 @@ char *fgets(char *restrict s, int n, FILE *restrict f) n--; if ((*p++ = c) == '\n') break; } - *p = 0; + if (s) *p = 0; FUNLOCK(f);