문제

정말이 붙어 노력에 쓰는 코드를 압축을 해제 파일 또는 디렉토리에 iPhone.

아래의 몇 가지 예제 코드에 사용하는 시도하고 압축을 해제한 간단한 텍스트 파일입니다.

그것은 압축 해제 파일이지만 그 손상되었습니다.

(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);  
}
도움이 되었습니까?

해결책

"sample.zip"이 실제로 GZIP로 만들어 졌습니까? .zip 확장자는 일반적으로 Winzip에서 생성 된 아카이브에 사용됩니다. Zlib을 사용하여 압축 해제 할 수도 있지만 헤더를 구문 분석하고 다른 루틴을 사용해야합니다.

확인하려면 파일의 첫 두 바이트를 살펴보십시오. 'PK'라면 Winzip이고 0x1f8b 인 경우 gzip입니다.

이것은 iPhone 특정이기 때문에 이것을 살펴보십시오. iPhone SDK 포럼 토론 어디 미니 팁 언급되어 있습니다. 이것이 WinZip 파일을 처리 할 수있는 것 같습니다.

그러나 그것이 실제로 Winzip 파일이라면, 당신은 winzip 사양 그리고 파일을 직접 구문 분석하려고 노력하십시오. 기본적으로 일부 헤더 값을 구문 분석하고 압축 스트림 위치를 찾고 Zlib 루틴을 사용하여 압축을 압축해야합니다.

다른 팁

나는 쉬운 솔루션을 원했고 여기에서 좋아하는 솔루션을 찾지 못했기 때문에 원하는 것을 수행하기 위해 라이브러리를 수정했습니다. 당신은 찾을 수 있습니다 ssziparchive 유용한. (그건 그렇고 zip 파일을 만들 수도 있습니다.)

용법:

NSString *path = @"path_to_your_zip_file";
NSString *destination = @"path_to_the_folder_where_you_want_it_unzipped";
[SSZipArchive unzipFileAtPath:path toDestination:destination];

이 코드는 gzip에게 잘 작동했습니다.

데이터베이스는 다음과 같이 준비되었습니다 : gzip foo.db

열쇠는 gzread ()를 통해 반복되는 것이 었습니다. 위의 예는 첫 번째 청크 바이트 만 읽습니다.

#import <zlib.h>
#define CHUNK 16384


  NSLog(@"testing unzip of database");
  start = [NSDate date];
  NSString *zippedDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"foo.db.gz"];
  NSString *unzippedDBPath = [documentsDirectory stringByAppendingPathComponent:@"foo2.db"];
  gzFile file = gzopen([zippedDBPath UTF8String], "rb");
  FILE *dest = fopen([unzippedDBPath UTF8String], "w");
  unsigned char buffer[CHUNK];
  int uncompressedLength;
  while (uncompressedLength = gzread(file, buffer, CHUNK) ) {
    // got data out of our file
    if(fwrite(buffer, 1, uncompressedLength, dest) != uncompressedLength || ferror(dest)) {
      NSLog(@"error writing data");
    }
  }
  fclose(dest);
  gzclose(file);
  NSLog(@"Finished unzipping database");

또한 77 초 안에 33MB를 130MB로 압축 할 수 있습니다.

이 코드는 모든 .zip 파일을 앱 문서 디렉토리로 압축하고 앱 리소스에서 파일을 가져옵니다.

self.fileManager = [NSFileManager defaultManager];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSLog(@"document directory path:%@",paths);

self.documentDirectory = [paths objectAtIndex:0];

NSString *filePath = [NSString stringWithFormat:@"%@/abc", self.documentDirectory];

NSLog(@"file path is:%@",filePath);

NSString *fileContent = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"data.zip"];


NSData *unzipData = [NSData dataWithContentsOfFile:fileContent];

[self.fileManager createFileAtPath:filePath contents:unzipData attributes:nil];

// here we go, unzipping code

ZipArchive *zipArchive = [[ZipArchive alloc] init];

if ([zipArchive UnzipOpenFile:filePath])
{
    if ([zipArchive UnzipFileTo:self.documentDirectory overWrite:NO])
    {
        NSLog(@"Archive unzip success");
        [self.fileManager removeItemAtPath:filePath error:NULL];
    }
    else
    {
        NSLog(@"Failure to unzip archive");
    }
}
else
{
    NSLog(@"Failure to open archive");
}
[zipArchive release];

임의의 zip 파일을 압축하기가 정말 어렵습니다. 복잡한 파일 형식이며 파일에 내부적으로 사용될 수있는 다양한 압축 루틴이 있습니다. Info-Zip에는 자유롭게 면허가 가능한 코드가 있습니다.http://www.info-zip.org/unzip.html) 해킹을 통해 iPhone에서 작업 할 수 있지만 API는 솔직히 끔찍합니다. 사령관 인수를 가짜 '메인'으로 전달하는 것이 포함되어있어 압축을 실행하는 것을 시뮬레이션합니다 (코드가 결코 공정하지 않기 때문입니다. 우선 이와 같이 사용되도록 설계된 라이브러리 기능은 나중에 볼트로 고정되었습니다).

압축을 풀려고하는 파일이 어디에서 나오는지 제어 할 수있는 경우, 나는 고도로 지퍼 대신 다른 압축 시스템을 사용하는 것이 좋습니다. 유연성과 유비쿼터스는 개인 간 파일 아카이브를 직접 대면하는 데 도움이되지만 자동화하는 것은 매우 어색합니다.

Zlib은 .zip 파일을 열기위한 것이 아니지만 운이 좋지 않습니다. Zlib의 Contrib 디렉토리에는 Zlib을 사용하여 .zip 파일을 열 수있는 MINIZIP가 포함되어 있습니다.

SDK에 번들로 번들리지 않을 수 있지만 Zlib의 번들 버전을 사용할 수 있습니다. Zlib 소스의 사본을 잡고 Contrib/Minizip을보십시오.

나는 iPhone을 사용하지 않았지만보고 싶을 수도 있습니다. gzip, 많은 플랫폼에서 사용할 수있는 매우 휴대용 오픈 소스 지퍼 라이브러리입니다.

나는 몇 가지 운 테스트에서 이 아이폰 시뮬레이터:

NSArray *paths = 
   NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *saveLocation = 
   [documentsDirectory stringByAppendingString:@"myfile.zip"];

NSFileManager* fileManager = [NSFileManager defaultManager];

if ([fileManager fileExistsAtPath:saveLocation]) {
    [fileManager removeItemAtPath:saveLocation error:nil];

}

NSURLRequest *theRequest = 
             [NSURLRequest requestWithURL:
                [NSURL URLWithString:@"http://example.com/myfile.zip"]
             cachePolicy:NSURLRequestUseProtocolCachePolicy
             timeoutInterval:60.0];    

NSData *received = 
             [NSURLConnection sendSynchronousRequest:theRequest 
                              returningResponse:nil error:nil];    

if ([received writeToFile:saveLocation atomically:TRUE]) {      
    NSString *cmd = 
       [NSString stringWithFormat:@"unzip \"%@\" -d\"%@\"", 
       saveLocation, documentsDirectory];       

    // Here comes the magic...
    system([cmd UTF8String]);       
}

그것은 쉽게 보고 이에 대해 조롱 zlib...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top