Really stuck on trying to write code to unzip a file or directory on the iPhone.
Below is some sample code that I’m using to try and unzip a simple text file.
It unzips the file but its corrupt.
(void)loadView { NSString *DOCUMENTS_FOLDER = [NSHomeDirectory() stringByAppendingPathComponent:@'Documents']; NSString *path = [DOCUMENTS_FOLDER stringByAppendingPathComponent:@'sample.zip']; NSString *unzipeddest = [DOCUMENTS_FOLDER stringByAppendingPathComponent:@'test.txt']; gzFile file = gzopen([path UTF8String], 'rb'); FILE *dest = fopen([unzipeddest UTF8String], 'w'); unsigned char buffer[CHUNK]; int uncompressedLength = gzread(file, buffer, CHUNK); if(fwrite(buffer, 1, uncompressedLength, dest) != uncompressedLength || ferror(dest)) { NSLog(@'error writing data'); } else{ } fclose(dest); gzclose(file); }
Has ‘sample.zip’ really been created with gZip? The .zip extension usually is used for archives created by WinZip. Those can also be decompressed using zLib, but you’d have to parse the header and use other routines.
To check, have a look at the first two bytes of the file. If it is ‘PK’, it’s WinZip, if it’s 0x1F8B, it’s gZip.
Because this is iPhone specific, have a look at this iPhone SDK forum discussion where miniZip is mentioned. It seems this can handle WinZip files.
But if it’s really a WinZip file, you should have a look at the WinZip specification and try to parse the file yourself. It basically should be parsing some header values, seeking the compressed stream position and using zLib routines to decompress it.