X-Git-Url: http://nsz.repo.hu/git/?a=blobdiff_plain;f=src%2Fstdio%2Ffgets.c;h=6171f398dacb4170a5a1227d515788d5457b252e;hb=0beb9dfbecad38af9759b1e83eeb007e28b70abb;hp=3135a69a2b9ebfe7b8475af708295c9e7e626056;hpb=e3cd6c5c265cd481db6e0c5b529855d99f0bda30;p=musl diff --git a/src/stdio/fgets.c b/src/stdio/fgets.c index 3135a69a..6171f398 100644 --- a/src/stdio/fgets.c +++ b/src/stdio/fgets.c @@ -1,31 +1,36 @@ #include "stdio_impl.h" +#include #define MIN(a,b) ((a)<(b) ? (a) : (b)) -char *fgets(char *s, int n, FILE *f) +char *fgets(char *restrict s, int n, FILE *restrict f) { char *p = s; unsigned char *z; 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; @@ -33,7 +38,7 @@ char *fgets(char *s, int n, FILE *f) n--; if ((*p++ = c) == '\n') break; } - *p = 0; + if (s) *p = 0; FUNLOCK(f);