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