fgets.c 718 B

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