fread.c 678 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #include "stdio_impl.h"
  2. #include <string.h>
  3. #define MIN(a,b) ((a)<(b) ? (a) : (b))
  4. size_t fread(void *restrict destv, size_t size, size_t nmemb, FILE *restrict f)
  5. {
  6. unsigned char *dest = destv;
  7. size_t len = size*nmemb, l = len, k;
  8. FLOCK(f);
  9. f->mode |= f->mode-1;
  10. if (f->rend - f->rpos > 0) {
  11. /* First exhaust the buffer. */
  12. k = MIN(f->rend - f->rpos, l);
  13. memcpy(dest, f->rpos, k);
  14. f->rpos += k;
  15. dest += k;
  16. l -= k;
  17. }
  18. /* Read the remainder directly */
  19. for (; l; l-=k, dest+=k) {
  20. k = __toread(f) ? 0 : f->read(f, dest, l);
  21. if (k+1<=1) {
  22. FUNLOCK(f);
  23. return (len-l)/size;
  24. }
  25. }
  26. FUNLOCK(f);
  27. return nmemb;
  28. }
  29. weak_alias(fread, fread_unlocked);