zio.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * zio.c
  3. * a generic input stream interface
  4. * $Id: zio.c,v 1.1 1997/06/16 16:50:22 roberto Exp roberto $
  5. */
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include "zio.h"
  10. /* ----------------------------------------------------- memory buffers --- */
  11. static int zmfilbuf(ZIO* z)
  12. {
  13. return EOZ;
  14. }
  15. ZIO* zmopen(ZIO* z, char* b, int size)
  16. {
  17. if (b==NULL) return NULL;
  18. z->n=size;
  19. z->p= (unsigned char *)b;
  20. z->filbuf=zmfilbuf;
  21. z->u=NULL;
  22. return z;
  23. }
  24. /* ------------------------------------------------------------ strings --- */
  25. ZIO* zsopen(ZIO* z, char* s)
  26. {
  27. if (s==NULL) return NULL;
  28. return zmopen(z,s,strlen(s));
  29. }
  30. /* -------------------------------------------------------------- FILEs --- */
  31. static int zffilbuf(ZIO* z)
  32. {
  33. int n=fread(z->buffer,1,ZBSIZE,z->u);
  34. if (n==0) return EOZ;
  35. z->n=n-1;
  36. z->p=z->buffer;
  37. return *(z->p++);
  38. }
  39. ZIO* zFopen(ZIO* z, FILE* f)
  40. {
  41. if (f==NULL) return NULL;
  42. z->n=0;
  43. z->p=z->buffer;
  44. z->filbuf=zffilbuf;
  45. z->u=f;
  46. return z;
  47. }
  48. /* --------------------------------------------------------------- read --- */
  49. int zread(ZIO *z, void *b, int n)
  50. {
  51. while (n) {
  52. int m;
  53. if (z->n == 0) {
  54. if (z->filbuf(z) == EOZ)
  55. return n; /* retorna quantos faltaram ler */
  56. zungetc(z); /* poe o resultado de filbuf no buffer */
  57. }
  58. m = (n <= z->n) ? n : z->n; /* minimo de n e z->n */
  59. memcpy(b, z->p, m);
  60. z->n -= m;
  61. z->p += m;
  62. b = (char *)b + m;
  63. n -= m;
  64. }
  65. return 0;
  66. }