fread.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. /*
  10. * pANS stdio -- fread
  11. */
  12. #include "iolib.h"
  13. #define BIGN (BUFSIZ/2)
  14. int32_t fread(void *p, int32_t recl, int32_t nrec, FILE *f){
  15. char *s;
  16. int n, d, c;
  17. s=(char *)p;
  18. n=recl*nrec;
  19. while(n>0){
  20. d=f->wp-f->rp;
  21. if(d>0){
  22. if(d>n)
  23. d=n;
  24. memmove(s, f->rp, d);
  25. f->rp+=d;
  26. }else{
  27. if(n >= BIGN && f->state==RD && !(f->flags&STRING) && f->buf!=f->unbuf){
  28. d=read(f->fd, s, n);
  29. if(d<=0){
  30. f->state=(d==0)?END:ERR;
  31. goto ret;
  32. }
  33. }else{
  34. c=_IO_getc(f);
  35. if(c==EOF)
  36. goto ret;
  37. *s=c;
  38. d=1;
  39. }
  40. }
  41. s+=d;
  42. n-=d;
  43. }
  44. ret:
  45. return (s-(char *)p)/(recl?recl:1);
  46. }