rewrite popen to use posix_spawn instead of fragile vfork hacks
[musl] / src / stdio / fgets.c
1 #include "stdio_impl.h"
2 #include <string.h>
3
4 #define MIN(a,b) ((a)<(b) ? (a) : (b))
5
6 char *fgets(char *restrict s, int n, FILE *restrict f)
7 {
8         char *p = s;
9         unsigned char *z;
10         size_t k;
11         int c;
12
13         if (n--<=1) {
14                 if (n) return 0;
15                 *s = 0;
16                 return s;
17         }
18
19         FLOCK(f);
20
21         while (n) {
22                 z = memchr(f->rpos, '\n', f->rend - f->rpos);
23                 k = z ? z - f->rpos + 1 : f->rend - f->rpos;
24                 k = MIN(k, n);
25                 memcpy(p, f->rpos, k);
26                 f->rpos += k;
27                 p += k;
28                 n -= k;
29                 if (z || !n) break;
30                 if ((c = getc_unlocked(f)) < 0) {
31                         if (p==s || !feof(f)) s = 0;
32                         break;
33                 }
34                 n--;
35                 if ((*p++ = c) == '\n') break;
36         }
37         *p = 0;
38
39         FUNLOCK(f);
40
41         return s;
42 }
43
44 weak_alias(fgets, fgets_unlocked);