OLD | NEW |
1 #include "stdio_impl.h" | 1 #include "stdio_impl.h" |
2 #include <string.h> | 2 #include <string.h> |
3 | 3 |
4 #define MIN(a,b) ((a)<(b) ? (a) : (b)) | 4 #define MIN(a, b) ((a) < (b) ? (a) : (b)) |
5 | 5 |
6 char *fgets(char *restrict s, int n, FILE *restrict f) | 6 char* fgets(char* restrict s, int n, FILE* restrict f) { |
7 { | 7 char* p = s; |
8 » char *p = s; | 8 unsigned char* z; |
9 » unsigned char *z; | 9 size_t k; |
10 » size_t k; | 10 int c; |
11 » int c; | |
12 | 11 |
13 » FLOCK(f); | 12 FLOCK(f); |
14 | 13 |
15 » if (n--<=1) { | 14 if (n-- <= 1) { |
16 » » f->mode |= f->mode-1; | 15 f->mode |= f->mode - 1; |
17 » » FUNLOCK(f); | 16 FUNLOCK(f); |
18 » » if (n) return 0; | 17 if (n) |
19 » » *s = 0; | 18 return 0; |
20 » » return s; | 19 *s = 0; |
21 » } | 20 return s; |
| 21 } |
22 | 22 |
23 » while (n) { | 23 while (n) { |
24 » » z = memchr(f->rpos, '\n', f->rend - f->rpos); | 24 z = memchr(f->rpos, '\n', f->rend - f->rpos); |
25 » » k = z ? z - f->rpos + 1 : f->rend - f->rpos; | 25 k = z ? z - f->rpos + 1 : f->rend - f->rpos; |
26 » » k = MIN(k, n); | 26 k = MIN(k, n); |
27 » » memcpy(p, f->rpos, k); | 27 memcpy(p, f->rpos, k); |
28 » » f->rpos += k; | 28 f->rpos += k; |
29 » » p += k; | 29 p += k; |
30 » » n -= k; | 30 n -= k; |
31 » » if (z || !n) break; | 31 if (z || !n) |
32 » » if ((c = getc_unlocked(f)) < 0) { | 32 break; |
33 » » » if (p==s || !feof(f)) s = 0; | 33 if ((c = getc_unlocked(f)) < 0) { |
34 » » » break; | 34 if (p == s || !feof(f)) |
35 » » } | 35 s = 0; |
36 » » n--; | 36 break; |
37 » » if ((*p++ = c) == '\n') break; | 37 } |
38 » } | 38 n--; |
39 » if (s) *p = 0; | 39 if ((*p++ = c) == '\n') |
| 40 break; |
| 41 } |
| 42 if (s) |
| 43 *p = 0; |
40 | 44 |
41 » FUNLOCK(f); | 45 FUNLOCK(f); |
42 | 46 |
43 » return s; | 47 return s; |
44 } | 48 } |
45 | 49 |
46 weak_alias(fgets, fgets_unlocked); | 50 weak_alias(fgets, fgets_unlocked); |
OLD | NEW |