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