iconv: add aliases for GBK
[musl.git] / src / stdio / fgets.c
blob4a100b3937bf007c6a2cd77ea9452405ccb1e16d
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<1) return 0;
19 *s = 0;
20 return s;
22 n--;
24 while (n) {
25 if (f->rpos != f->rend) {
26 z = memchr(f->rpos, '\n', f->rend - f->rpos);
27 k = z ? z - f->rpos + 1 : f->rend - f->rpos;
28 k = MIN(k, n);
29 memcpy(p, f->rpos, k);
30 f->rpos += k;
31 p += k;
32 n -= k;
33 if (z || !n) break;
35 if ((c = getc_unlocked(f)) < 0) {
36 if (p==s || !feof(f)) s = 0;
37 break;
39 n--;
40 if ((*p++ = c) == '\n') break;
42 if (s) *p = 0;
44 FUNLOCK(f);
46 return s;
49 weak_alias(fgets, fgets_unlocked);