fwrite.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 -- fwrite
  11. */
  12. #include "iolib.h"
  13. #define BIGN (BUFSIZ/2)
  14. int32_t fwrite(const void *p, int32_t recl, int32_t nrec, FILE *f){
  15. char *s;
  16. int n, d;
  17. s=(char *)p;
  18. n=recl*nrec;
  19. while(n>0){
  20. d=f->rp-f->wp;
  21. if(d>0){
  22. if(d>n)
  23. d=n;
  24. memmove(f->wp, s, d);
  25. f->wp+=d;
  26. }else{
  27. if(n>=BIGN && f->state==WR && !(f->flags&(STRING|LINEBUF)) && f->buf!=f->unbuf){
  28. d=f->wp-f->buf;
  29. if(d>0){
  30. if(f->flags&APPEND)
  31. seek(f->fd, 0L, 2);
  32. if(write(f->fd, f->buf, d)!=d){
  33. f->state=ERR;
  34. goto ret;
  35. }
  36. f->wp=f->rp=f->buf;
  37. }
  38. if(f->flags&APPEND)
  39. seek(f->fd, 0L, 2);
  40. d=write(f->fd, s, n);
  41. if(d<=0){
  42. f->state=ERR;
  43. goto ret;
  44. }
  45. }else{
  46. if(_IO_putc(*s, f)==EOF)
  47. goto ret;
  48. d=1;
  49. }
  50. }
  51. s+=d;
  52. n-=d;
  53. }
  54. ret:
  55. return (s-(char *)p)/(recl?recl:1);
  56. }