1 #include "stdio_impl.h"
2 #include <string.h>
3
4 #ifndef MIN
5 #define MIN(a,b) ((a)<(b) ? (a) : (b))
6 #endif
7
fgets(char * restrict s,int n,FILE * restrict f)8 char *fgets(char *restrict s, int n, FILE *restrict f)
9 {
10 char *p = s;
11 unsigned char *z;
12 size_t k;
13 int c;
14
15 FLOCK(f);
16
17 if (n--<=1) {
18 f->mode |= f->mode-1;
19 FUNLOCK(f);
20 if (n) return 0;
21 *s = 0;
22 return s;
23 }
24
25 while (n) {
26 if (f->rpos != f->rend) {
27 z = memchr(f->rpos, '\n', f->rend - f->rpos);
28 k = z ? z - f->rpos + 1 : f->rend - f->rpos;
29 k = MIN(k, n);
30 memcpy(p, f->rpos, k);
31 f->rpos += k;
32 p += k;
33 n -= k;
34 if (z || !n) break;
35 }
36 if ((c = getc_unlocked(f)) < 0) {
37 if (p==s || !feof(f)) s = 0;
38 break;
39 }
40 n--;
41 if ((*p++ = c) == '\n') break;
42 }
43 if (s) *p = 0;
44
45 FUNLOCK(f);
46
47 return s;
48 }
49
50 weak_alias(fgets, fgets_unlocked);
51