1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
/*
* Copyright (c) 2011, Novell Inc.
*
* This program is licensed under the BSD license, read LICENSE.BSD
* for further information
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <zlib.h>
#include <fcntl.h>
#include "solv_xfopen.h"
static ssize_t cookie_gzread(void *cookie, char *buf, size_t nbytes)
{
return gzread((gzFile *)cookie, buf, nbytes);
}
static int
cookie_gzclose(void *cookie)
{
return gzclose((gzFile *)cookie);
}
static FILE *mygzfopen(gzFile* gzf)
{
#ifdef HAVE_FUNOPEN
return funopen(
gzf, (int (*)(void *, char *, int))cookie_gzread,
(int (*)(void *, const char *, int))NULL, /* writefn */
(fpos_t (*)(void *, fpos_t, int))NULL, /* seekfn */
cookie_gzclose
);
#elif defined(HAVE_FOPENCOOKIE)
cookie_io_functions_t cio;
memset(&cio, 0, sizeof(cio));
cio.read = cookie_gzread;
cio.close = cookie_gzclose;
return fopencookie(gzf, "r", cio);
#else
# error Need to implement custom I/O
#endif
}
FILE *
solv_xfopen(const char *fn, const char *mode)
{
char *suf;
gzFile *gzf;
if (!fn)
return 0;
if (!mode)
mode = "r";
suf = strrchr(fn, '.');
if (!suf || strcmp(suf, ".gz") != 0)
return fopen(fn, mode);
gzf = gzopen(fn, mode);
if (!gzf)
return 0;
return mygzfopen(gzf);
}
FILE *
solv_xfopen_fd(const char *fn, int fd, const char *mode)
{
char *suf;
gzFile *gzf;
suf = fn ? strrchr(fn, '.') : 0;
if (!mode)
{
int fl = fcntl(fd, F_GETFL, 0);
if (fl == -1)
return 0;
fl &= O_RDONLY|O_WRONLY|O_RDWR;
if (fl == O_WRONLY)
mode = "w";
else if (fl == O_RDWR)
{
if (!suf || strcmp(suf, ".gz") != 0)
mode = "r+";
else
mode = "r";
}
else
mode = "r";
}
if (!suf || strcmp(suf, ".gz") != 0)
return fdopen(fd, mode);
gzf = gzdopen(fd, mode);
if (!gzf)
return 0;
return mygzfopen(gzf);
}
|