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