fix unsynchronized access to FILE structure in fflush(0)
[musl.git] / src / stdio / fgets.c
blobd3f9819e82eec3a5707805d5ae5b661a78adec30
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 z = memchr(f->rpos, '\n', f->rend - f->rpos);
25 k = z ? z - f->rpos + 1 : f->rend - f->rpos;
26 k = MIN(k, n);
27 memcpy(p, f->rpos, k);
28 f->rpos += k;
29 p += k;
30 n -= k;
31 if (z || !n) break;
32 if ((c = getc_unlocked(f)) < 0) {
33 if (p==s || !feof(f)) s = 0;
34 break;
36 n--;
37 if ((*p++ = c) == '\n') break;
39 if (s) *p = 0;
41 FUNLOCK(f);
43 return s;
46 weak_alias(fgets, fgets_unlocked);