[Mac][iOS]minizip ファイルの圧縮と解凍 | Cocoa練習帳

[Mac][iOS]minizip ファイルの圧縮と解凍

前回のZipArchiveライブラリが内部で利用していたminizipライブラリを直接利用する事に挑戦する。


minizipを直接利用する利点は、複数のファイルが固められて圧縮されていた場合、全てを解凍するのではなくて、必要なファイルのみにアクセスする事が可能になる事だ。




以下のMinizipのサイトからminizipライブラリ一式をダウンロードする。




Minizip



minizip一式には、コマンドラインのプログラム用のソースファイルが含まれているので、ライブラリとして使用する場合に必要となる、以下のファイルのみをプロジェクトに追加する。




crypt.h
ioapi.c
ioapi.h
mztools.c
mztools.h
unzip.c
unzip.h
zip.c
zip.h



プロジェクトに以下のライブラリを追加する。




libz.dylib



文書オープンのダイアログで指定したzipファイルの中身を出力するコードを追加する。




@interface AppDelegate : NSObject 
        :
- (IBAction)openDocument:(id)sender;
@end



#import "unzip.h"
        :
@interface AppDelegate ()
- (void)unzip:(NSString *)path;
@end
 
@implementation AppDelegate
        :
- (IBAction)openDocument:(id)sender
{
    DBGMSG(@"%s", __func__);
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel beginSheetModalForWindow:self.window
                  completionHandler:^(NSInteger returnCode){
        NSURL       *pathToFile = nil;
        NSString    *path = nil;
         
        if (returnCode == NSOKButton) {
            pathToFile = [[panel URLs] objectAtIndex:0];
            path = [pathToFile path];
            DBGMSG(@"%@", pathToFile);
            DBGMSG(@"%@", path);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self unzip:path];
            });
        }
    }];
}
 
- (void)unzip:(NSString *)path
{
    DBGMSG(@"%s, %@", __func__, path);
    int error = UNZ_OK;
    unzFile file = NULL;
    file = unzOpen([path UTF8String]);
    unzGoToFirstFile(file);
    while (error == UNZ_OK) {
        unz_file_info   fileInfo;
        char            filename[PATH_MAX];
        unzGetCurrentFileInfo(file, &fileInfo, filename, PATH_MAX, NULL, 0, NULL, 0);
        DBGMSG(@"%s", filename);
        error = unzGoToNextFile(file);
    }
    unzClose(file);
}
@end



以下のディレクトリ構造のフォルダをzipで圧縮する。





junk
 | file01.txt
 | file02.txt
 +- folder01
 |    file11.txt
 |    file12.txt
 +- folder02
      file21.txt
      file22.txt



これを先ほどのコードでディレクトリ構造をデバッグ出力した結果の抜粋が以下。




junk/
junk/file01.txt
junk/file02.txt
junk/folder01/
junk/folder01/file11.txt
junk/folder01/file12.txt
junk/folder02/
junk/folder02/file21.txt
junk/folder02/file22.txt



ソースコード
GitHubからどうぞ。

https://github.com/murakami/workbook/tree/master/mac/Zip


関連情報
zlib

A Massively Spiffy Yet Delicately Unobtrusive Compression Library

Minizip

Zip and UnZIp additionnal library

ZipArchive

An Objective C class for zip/unzip on iPhone and Mac OSX

objective-zip

An iOS wrapper for ZLib and MiniZip

Objective-CでZIPアーカイブを読み取る

@marvelphさんのブログです。