-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathZipFile.m
111 lines (90 loc) · 2.28 KB
/
ZipFile.m
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
//
// ZipFile.m
// ZipFile
//
// Created by Kenji Nishishiro <[email protected]> on 10/05/08.
// Copyright 2010 Kenji Nishishiro. All rights reserved.
//
#import "ZipFile.h"
@implementation ZipFile
static const int CASE_SENSITIVITY = 0;
static const unsigned int BUFFER_SIZE = 8192;
- (id)initWithFileAtPath:(NSString *)path {
NSAssert(path, @"path");
if (self = [super init]) {
path_ = [path retain];
unzipFile_ = NULL;
}
return self;
}
- (void)dealloc {
NSAssert(!unzipFile_, @"!unzipFile_");
[path_ release];
[super dealloc];
}
- (BOOL)open {
NSAssert(!unzipFile_, @"!unzipFile_");
unzipFile_ = unzOpen64([path_ UTF8String]);
return unzipFile_ != NULL;
}
- (void)close {
NSAssert(unzipFile_, @"unzipFile_");
unzClose(unzipFile_);
unzipFile_ = NULL;
}
- (NSData *)readWithFileName:(NSString *)fileName maxLength:(NSUInteger)maxLength {
NSAssert(unzipFile_, @"unzipFile_");
NSAssert(fileName, @"fileName");
if (unzLocateFile(unzipFile_, [fileName UTF8String], CASE_SENSITIVITY) != UNZ_OK) {
return nil;
}
if (unzOpenCurrentFile(unzipFile_) != UNZ_OK) {
return nil;
}
NSMutableData *data = [NSMutableData data];
NSUInteger length = 0;
void *buffer = (void *)malloc(BUFFER_SIZE);
while (YES) {
unsigned size = length + BUFFER_SIZE <= maxLength ? BUFFER_SIZE : maxLength - length;
int readLength = unzReadCurrentFile(unzipFile_, buffer, size);
if (readLength < 0) {
free(buffer);
unzCloseCurrentFile(unzipFile_);
return nil;
}
if (readLength > 0) {
[data appendBytes:buffer length:readLength];
length += readLength;
}
if (readLength == 0) {
break;
}
};
free(buffer);
unzCloseCurrentFile(unzipFile_);
return data;
}
- (NSArray *)fileNames {
NSAssert(unzipFile_, @"unzipFile_");
NSMutableArray *results = [NSMutableArray array];
if (unzGoToFirstFile(unzipFile_) != UNZ_OK) {
return nil;
}
while (YES) {
unz_file_info64 fileInfo;
char fileName[PATH_MAX];
if (unzGetCurrentFileInfo64(unzipFile_, &fileInfo, fileName, PATH_MAX, NULL, 0, NULL, 0) != UNZ_OK) {
return nil;
}
[results addObject:[NSString stringWithUTF8String:fileName]];
int error = unzGoToNextFile(unzipFile_);
if (error == UNZ_END_OF_LIST_OF_FILE) {
break;
}
if (error != UNZ_OK) {
return nil;
}
}
return results;
}
@end