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