-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileio.c
153 lines (130 loc) · 3.29 KB
/
fileio.c
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#include "shared.h"
/*
Load a normal file, or ZIP/GZ archive.
Returns NULL if an error occured.
*/
uint8 *load_archive(char *filename, int *file_size)
{
int size = 0;
uint8 *buf = NULL;
if(check_zip(filename))
{
unzFile *fd = NULL;
unz_file_info info;
int ret = 0;
/* Attempt to open the archive */
fd = unzOpen(filename);
if(!fd) return (NULL);
/* Go to first file in archive */
ret = unzGoToFirstFile(fd);
if(ret != UNZ_OK)
{
unzClose(fd);
return (NULL);
}
ret = unzGetCurrentFileInfo(fd, &info, NULL, 0, NULL, 0, NULL, 0);
if(ret != UNZ_OK)
{
unzClose(fd);
return (NULL);
}
/* Open the file for reading */
ret = unzOpenCurrentFile(fd);
if(ret != UNZ_OK)
{
unzClose(fd);
return (NULL);
}
/* Allocate file data buffer */
size = info.uncompressed_size;
buf = malloc(size);
if(!buf)
{
unzClose(fd);
return (NULL);
}
/* Read (decompress) the file */
ret = unzReadCurrentFile(fd, buf, info.uncompressed_size);
if(ret != info.uncompressed_size)
{
free(buf);
unzCloseCurrentFile(fd);
unzClose(fd);
return (NULL);
}
/* Close the current file */
ret = unzCloseCurrentFile(fd);
if(ret != UNZ_OK)
{
free(buf);
unzClose(fd);
return (NULL);
}
/* Close the archive */
ret = unzClose(fd);
if(ret != UNZ_OK)
{
free(buf);
return (NULL);
}
/* Update file size and return pointer to file data */
*file_size = size;
return (buf);
}
else
{
gzFile gd = NULL;
/* Open file */
gd = gzopen(filename, "rb");
if(!gd) return (0);
/* Get file size */
size = gzsize(gd);
/* Allocate file data buffer */
buf = malloc(size);
if(!buf)
{
gzclose(gd);
return (0);
}
/* Read file data */
gzread(gd, buf, size);
/* Close file */
gzclose(gd);
/* Update file size and return pointer to file data */
*file_size = size;
return (buf);
}
}
/*
Verifies if a file is a ZIP archive or not.
Returns: 1= ZIP archive, 0= not a ZIP archive
*/
int check_zip(char *filename)
{
uint8 buf[2];
FILE *fd = NULL;
fd = fopen(filename, "rb");
if(!fd) return (0);
fread(buf, 2, 1, fd);
fclose(fd);
if(memcmp(buf, "PK", 2) == 0) return (1);
return (0);
}
/*
Returns the size of a GZ compressed file.
*/
int gzsize(gzFile gd)
{
#define CHUNKSIZE (0x10000)
int size = 0, length = 0;
unsigned char buffer[CHUNKSIZE];
gzrewind(gd);
do {
size = gzread(gd, buffer, CHUNKSIZE);
if(size <= 0) break;
length += size;
} while (!gzeof(gd));
gzrewind(gd);
return (length);
#undef CHUNKSIZE
}