add TLSDESC support for 32-bit arm
[musl.git] / src / stdio / fgets.c
blob6171f398dacb4170a5a1227d515788d5457b252e
1 #include "stdio_impl.h"
2 #include <string.h>
4 #define MIN(a,b) ((a)<(b) ? (a) : (b))
6 char *fgets(char *restrict s, int n, FILE *restrict f)
8 char *p = s;
9 unsigned char *z;
10 size_t k;
11 int c;
13 FLOCK(f);
15 if (n--<=1) {
16 f->mode |= f->mode-1;
17 FUNLOCK(f);
18 if (n) return 0;
19 *s = 0;
20 return s;
23 while (n) {
24 if (f->rpos != f->rend) {
25 z = memchr(f->rpos, '\n', f->rend - f->rpos);
26 k = z ? z - f->rpos + 1 : f->rend - f->rpos;
27 k = MIN(k, n);
28 memcpy(p, f->rpos, k);
29 f->rpos += k;
30 p += k;
31 n -= k;
32 if (z || !n) break;
34 if ((c = getc_unlocked(f)) < 0) {
35 if (p==s || !feof(f)) s = 0;
36 break;
38 n--;
39 if ((*p++ = c) == '\n') break;
41 if (s) *p = 0;
43 FUNLOCK(f);
45 return s;
48 weak_alias(fgets, fgets_unlocked);