xref: /third_party/musl/src/stdio/fgets.c (revision 570af302)
1#include "stdio_impl.h"
2#include <string.h>
3#ifndef __LITEOS__
4#include "param_check.h"
5#endif
6
7#define MIN(a,b) ((a)<(b) ? (a) : (b))
8char *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#ifndef __LITEOS__
15	PARAM_CHECK(f);
16#endif
17	FLOCK(f);
18
19	if (n<=1) {
20		f->mode |= f->mode-1;
21		FUNLOCK(f);
22		if (n<1) return 0;
23		*s = 0;
24		return s;
25	}
26	n--;
27
28	while (n) {
29		if (f->rpos != f->rend) {
30			z = memchr(f->rpos, '\n', MIN(f->rend - f->rpos, n));
31			k = z ? z - f->rpos + 1 : f->rend - f->rpos;
32			k = MIN(k, n);
33			memcpy(p, f->rpos, k);
34			f->rpos += k;
35			p += k;
36			n -= k;
37			if (z || !n) break;
38		}
39		if ((c = getc_unlocked(f)) < 0) {
40			if (p==s || !feof(f)) s = 0;
41			break;
42		}
43		n--;
44		if ((*p++ = c) == '\n') break;
45	}
46	if (s) *p = 0;
47
48	FUNLOCK(f);
49
50	return s;
51}
52
53
54weak_alias(fgets, fgets_unlocked);
55