zio.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. /*
  2. * zio.c
  3. * a generic input stream interface
  4. * $Id: zio.c,v 1.5 1997/06/13 13:49:16 lhf Exp $
  5. */
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include "zio.h"
  10. #ifdef POPEN
  11. FILE *popen();
  12. int pclose();
  13. #else
  14. #define popen(x,y) NULL /* that is, popen always fails */
  15. #define pclose(x) (-1)
  16. #endif
  17. /* ----------------------------------------------------- memory buffers --- */
  18. static int zmfilbuf(ZIO* z)
  19. {
  20. return EOZ;
  21. }
  22. static int zmclose(ZIO* z)
  23. {
  24. return 1;
  25. }
  26. ZIO* zmopen(ZIO* z, char* b, int size)
  27. {
  28. if (b==NULL) return NULL;
  29. z->n=size;
  30. z->p= (unsigned char *)b;
  31. z->filbuf=zmfilbuf;
  32. z->close=zmclose;
  33. z->u=NULL;
  34. return z;
  35. }
  36. /* ------------------------------------------------------------ strings --- */
  37. ZIO* zsopen(ZIO* z, char* s)
  38. {
  39. if (s==NULL) return NULL;
  40. return zmopen(z,s,strlen(s));
  41. }
  42. /* -------------------------------------------------------------- FILEs --- */
  43. static int zffilbuf(ZIO* z)
  44. {
  45. int n=fread(z->buffer,1,ZBSIZE,z->u);
  46. if (n==0) return EOZ;
  47. z->n=n-1;
  48. z->p=z->buffer;
  49. return *(z->p++);
  50. }
  51. static int zfclose(ZIO* z)
  52. {
  53. if (z->u==stdin) return 0;
  54. return fclose(z->u);
  55. }
  56. ZIO* zFopen(ZIO* z, FILE* f)
  57. {
  58. if (f==NULL) return NULL;
  59. z->n=0;
  60. z->p=z->buffer;
  61. z->filbuf=zffilbuf;
  62. z->close=zfclose;
  63. z->u=f;
  64. return z;
  65. }
  66. ZIO* zfopen(ZIO* z, char* s, char* m)
  67. {
  68. return zFopen(z,fopen(s,m));
  69. }
  70. /* -------------------------------------------------------------- pipes --- */
  71. static int zpclose(ZIO* z)
  72. {
  73. return pclose(z->u);
  74. }
  75. ZIO* zpopen(ZIO* z, char* s, char* m)
  76. {
  77. z=zFopen(z,popen(s,m));
  78. if (z==NULL) return NULL;
  79. z->close=zpclose;
  80. return z;
  81. }
  82. /* --------------------------------------------------------------- read --- */
  83. int zread(ZIO *z, void *b, int n)
  84. {
  85. while (n) {
  86. int m;
  87. if (z->n == 0) {
  88. if (z->filbuf(z) == EOZ)
  89. return n; /* retorna quantos faltaram ler */
  90. zungetc(z); /* poe o resultado de filbuf no buffer */
  91. }
  92. m = (n <= z->n) ? n : z->n; /* minimo de n e z->n */
  93. memcpy(b, z->p, m);
  94. z->n -= m;
  95. z->p += m;
  96. b = (char *)b + m;
  97. n -= m;
  98. }
  99. return 0;
  100. }