fread.c 694 B

1234567891011121314151617181920212223242526272829303132333435363738
  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. if (!size) nmemb = 0;
  9. FLOCK(f);
  10. f->mode |= f->mode-1;
  11. if (f->rpos != f->rend) {
  12. /* First exhaust the buffer. */
  13. k = MIN(f->rend - f->rpos, l);
  14. memcpy(dest, f->rpos, k);
  15. f->rpos += k;
  16. dest += k;
  17. l -= k;
  18. }
  19. /* Read the remainder directly */
  20. for (; l; l-=k, dest+=k) {
  21. k = __toread(f) ? 0 : f->read(f, dest, l);
  22. if (!k) {
  23. FUNLOCK(f);
  24. return (len-l)/size;
  25. }
  26. }
  27. FUNLOCK(f);
  28. return nmemb;
  29. }
  30. weak_alias(fread, fread_unlocked);