aboutsummaryrefslogtreecommitdiff
path: root/zio.c
diff options
context:
space:
mode:
Diffstat (limited to 'zio.c')
-rw-r--r--zio.c117
1 files changed, 117 insertions, 0 deletions
diff --git a/zio.c b/zio.c
new file mode 100644
index 00000000..aa400f7d
--- /dev/null
+++ b/zio.c
@@ -0,0 +1,117 @@
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
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10#include "zio.h"
11
12#ifdef POPEN
13FILE *popen();
14int pclose();
15#else
16#define popen(x,y) NULL /* that is, popen always fails */
17#define pclose(x) (-1)
18#endif
19
20/* ----------------------------------------------------- memory buffers --- */
21
22static int zmfilbuf(ZIO* z)
23{
24 return EOZ;
25}
26
27static int zmclose(ZIO* z)
28{
29 return 1;
30}
31
32ZIO* zmopen(ZIO* z, char* b, int size)
33{
34 if (b==NULL) return NULL;
35 z->n=size;
36 z->p= (unsigned char *)b;
37 z->filbuf=zmfilbuf;
38 z->close=zmclose;
39 z->u=NULL;
40 return z;
41}
42
43/* ------------------------------------------------------------ strings --- */
44
45ZIO* zsopen(ZIO* z, char* s)
46{
47 if (s==NULL) return NULL;
48 return zmopen(z,s,strlen(s));
49}
50
51/* -------------------------------------------------------------- FILEs --- */
52
53static int zffilbuf(ZIO* z)
54{
55 int n=fread(z->buffer,1,ZBSIZE,z->u);
56 if (n==0) return EOZ;
57 z->n=n-1;
58 z->p=z->buffer;
59 return *(z->p++);
60}
61
62static int zfclose(ZIO* z)
63{
64 if (z->u==stdin) return 0;
65 return fclose(z->u);
66}
67
68ZIO* zFopen(ZIO* z, FILE* f)
69{
70 if (f==NULL) return NULL;
71 z->n=0;
72 z->p=z->buffer;
73 z->filbuf=zffilbuf;
74 z->close=zfclose;
75 z->u=f;
76 return z;
77}
78
79ZIO* zfopen(ZIO* z, char* s, char* m)
80{
81 return zFopen(z,fopen(s,m));
82}
83
84/* -------------------------------------------------------------- pipes --- */
85
86static int zpclose(ZIO* z)
87{
88 return pclose(z->u);
89}
90
91ZIO* zpopen(ZIO* z, char* s, char* m)
92{
93 z=zFopen(z,popen(s,m));
94 if (z==NULL) return NULL;
95 z->close=zpclose;
96 return z;
97}
98
99/* --------------------------------------------------------------- read --- */
100int zread(ZIO *z, void *b, int n)
101{
102 while (n) {
103 int m;
104 if (z->n == 0) {
105 if (z->filbuf(z) == EOZ)
106 return n; /* retorna quantos faltaram ler */
107 zungetc(z); /* poe o resultado de filbuf no buffer */
108 }
109 m = (n <= z->n) ? n : z->n; /* minimo de n e z->n */
110 memcpy(b, z->p, m);
111 z->n -= m;
112 z->p += m;
113 b = (char *)b + m;
114 n -= m;
115 }
116 return 0;
117}