1
0

fgets.c 758 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. if (f->rpos != f->rend) {
  20. z = memchr(f->rpos, '\n', f->rend - f->rpos);
  21. k = z ? z - f->rpos + 1 : f->rend - f->rpos;
  22. k = MIN(k, n);
  23. memcpy(p, f->rpos, k);
  24. f->rpos += k;
  25. p += k;
  26. n -= k;
  27. if (z || !n) break;
  28. }
  29. if ((c = getc_unlocked(f)) < 0) {
  30. if (p==s || !feof(f)) s = 0;
  31. break;
  32. }
  33. n--;
  34. if ((*p++ = c) == '\n') break;
  35. }
  36. if (s) *p = 0;
  37. FUNLOCK(f);
  38. return s;
  39. }
  40. weak_alias(fgets, fgets_unlocked);