initial check-in, version 0.5.0
[musl] / src / stdio / fgets.c
1 #include "stdio_impl.h"
2
3 #define MIN(a,b) ((a)<(b) ? (a) : (b))
4
5 char *fgets(char *s, int n, FILE *f)
6 {
7         char *p = s;
8         unsigned char *z;
9         size_t k;
10
11         if (!n--) return 0;
12
13         FLOCK(f);
14
15         while (n && !feof(f)) {
16                 z = memchr(f->rpos, '\n', f->rend - f->rpos);
17                 k = z ? z - f->rpos + 1 : f->rend - f->rpos;
18                 k = MIN(k, n);
19                 memcpy(p, f->rpos, k);
20                 f->rpos += k;
21                 p += k;
22                 n -= k;
23                 if (z) break;
24                 __underflow(f);
25         }
26         *p = 0;
27         if (ferror(f)) p = s;
28
29         FUNLOCK(f);
30
31         return (p == s) ? 0 : s;
32 }
33
34 weak_alias(fgets, fgets_unlocked);