diff --git a/porting/linux/user/src/stdio/fgets.c b/porting/linux/user/src/stdio/fgets.c index 819606a6e182556c0cc71b4c0dcadc0ca91c4cb8..4a2e81fd943e7ad2a1adc4bbe6cc00c88ba9eb0e 100644 --- a/porting/linux/user/src/stdio/fgets.c +++ b/porting/linux/user/src/stdio/fgets.c @@ -2,7 +2,6 @@ #include #define MIN(a,b) ((a)<(b) ? (a) : (b)) - char *fgets(char *restrict s, int n, FILE *restrict f) { char *p = s; @@ -15,42 +14,35 @@ char *fgets(char *restrict s, int n, FILE *restrict f) if (n--<=1) { f->mode |= f->mode-1; FUNLOCK(f); - if (n) { - return NULL; - } - *s = '\0'; + if (n) return 0; + *s = 0; return s; } while (n) { - if (f->rpos == f->rend && __fill_buffer(f)) { - if (p == s || !feof(f)) { - s = 0; - } - break; + if (f->rpos != f->rend) { + z = memchr(f->rpos, '\n', MIN(f->rend - f->rpos, n)); + 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; } - - /* search minimal length */ - k = MIN(f->rend - f->rpos, n); - z = memchr(f->rpos, '\n', k); - if (z != NULL) { - k = z - f->rpos + 1; - } - memcpy(p, f->rpos, k); - f->rpos += k; - p += k; - n -= k; - if (z || !n) { + if ((c = getc_unlocked(f)) < 0) { + if (p==s || !feof(f)) s = 0; break; } + n--; + if ((*p++ = c) == '\n') break; } - if (s) { - *p = 0; - } + if (s) *p = 0; FUNLOCK(f); return s; } + weak_alias(fgets, fgets_unlocked);