xref: /freebsd/lib/libz/zopen.c (revision 5e3190f700637fcfc1a52daeaa4a031fdd2557c7)
1 /*
2  * Public domain stdio wrapper for libz, written by Johan Danielsson.
3  */
4 
5 #include <sys/cdefs.h>
6 #include <stdio.h>
7 #include <zlib.h>
8 
9 FILE *zopen(const char *fname, const char *mode);
10 FILE *zdopen(int fd, const char *mode);
11 
12 /* convert arguments */
13 static int
14 xgzread(void *cookie, char *data, int size)
15 {
16     return gzread(cookie, data, size);
17 }
18 
19 static int
20 xgzwrite(void *cookie, const char *data, int size)
21 {
22     return gzwrite(cookie, (void*)data, size);
23 }
24 
25 static int
26 xgzclose(void *cookie)
27 {
28     return gzclose(cookie);
29 }
30 
31 static fpos_t
32 xgzseek(void *cookie,  fpos_t offset, int whence)
33 {
34 	return gzseek(cookie, (z_off_t)offset, whence);
35 }
36 
37 FILE *
38 zopen(const char *fname, const char *mode)
39 {
40     gzFile gz = gzopen(fname, mode);
41     if(gz == NULL)
42 	return NULL;
43 
44     if(*mode == 'r')
45 	return (funopen(gz, xgzread, NULL, xgzseek, xgzclose));
46     else
47 	return (funopen(gz, NULL, xgzwrite, xgzseek, xgzclose));
48 }
49 
50 FILE *
51 zdopen(int fd, const char *mode)
52 {
53 	gzFile gz;
54 
55 	gz = gzdopen(fd, mode);
56 	if (gz == NULL)
57 		return (NULL);
58 
59 	if (*mode == 'r')
60 		return (funopen(gz, xgzread, NULL, xgzseek, xgzclose));
61 	else
62 		return (funopen(gz, NULL, xgzwrite, xgzseek, xgzclose));
63 }
64