ios iPhone 解压码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/412982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:29:24  来源:igfitidea点击:

iPhone Unzip code

iosobjective-czipcompression

提问by TonyNeallon

Really stuck on trying to write code to unzip a file or directory on the iPhone.

真的坚持尝试编写代码来解压缩 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);  
}

采纳答案by schnaader

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.

“sample.zip”真的是用gZip创建的吗?.zip 扩展名通常用于由 WinZip 创建的档案。这些也可以使用 zLib 解压缩,但您必须解析标头并使用其他例程。

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.

要检查,请查看文件的前两个字节。如果是“PK”,则是 WinZip,如果是 0x1F8B,则是 gZip。

Because this is iPhone specific, have a look at this iPhone SDK forum discussionwhere miniZipis mentioned. It seems this can handle WinZip files.

因为这是特定于iPhone 的,请查看提及miniZip 的iPhone SDK 论坛讨论。看来这可以处理 WinZip 文件。

But if it's really a WinZip file, you should have a look at the WinZip specificationand 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.

但如果它真的是一个 WinZip 文件,您应该查看WinZip 规范并尝试自己解析该文件。它基本上应该解析一些标头值,寻找压缩流位置并使用 zLib 例程对其进行解压缩。

回答by Sam Soffes

I wanted an easy solution and didn't find one I liked here, so I modified a library to do what I wanted. You may find SSZipArchiveuseful. (It can also create zip files by the way.)

我想要一个简单的解决方案,但在这里没有找到我喜欢的解决方案,所以我修改了一个库来做我想做的。您可能会发现SSZipArchive很有用。(顺便说一下,它还可以创建 zip 文件。)

Usage:

用法:

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

回答by Carl Coryell-Martin

This code worked well for me for gzip:

这段代码对我来说很适合 gzip:

the database was prepared like this: gzip foo.db

数据库是这样准备的:gzip foo.db

the key was looping over the gzread(). The example above only reads the first CHUNK bytes.

关键是在 gzread() 上循环。上面的例子只读取第一个 CHUNK 字节。

#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");

Incidentally, I can unzip 33MB into 130MB in 77 seconds or about 1.7 MB uncompressed/second.

顺便说一句,我可以在 77 秒内将 33MB 解压缩为 130MB,或者大约 1.7 MB 未压缩/秒。

回答by marshad13

This code will unzip any .zip file into your app document directory and get file from app resources.

此代码会将任何 .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];

回答by th_in_gs

It's really hard to unzip any arbitrary zip file. It's a complex file format, and there are potentially many different compression routines that could have been used internally to the file. Info-ZIP has some freely licencable code to do it (http://www.info-zip.org/UnZip.html) that can be made to work on the iPhone with some hacking, but the API is frankly horrible - it involves passing command-line arguments to a fake 'main' that simulates the running of UnZIP (to be fair that's because their code was never designed to be used like this in the first place, the library functionality was bolted on afterwards).

解压缩任何任意 zip 文件真的很困难。这是一种复杂的文件格式,并且可能有许多不同的压缩例程可以在文件内部使用。Info-ZIP 有一些可免费许可的代码(http://www.info-zip.org/UnZip.html),可以通过一些黑客攻击在 iPhone 上运行,但坦率地说,API 很糟糕——它涉及将命令行参数传递给模拟 UnZIP 运行的假“main”(公平地说,这是因为他们的代码从来没有被设计成这样使用,后来库功能被栓上了)。

If you have any control of where the files you're trying to unzip are coming from, I highlyrecommend using another compression system instead of ZIP. It's flexibility and ubiquity make it great for passing archives of files around in person-to-person, but it's very awkward to automate.

如果您可以控制要解压缩的文件的来源,我强烈建议您使用其他压缩系统而不是 ZIP。它的灵活性和普遍性使其非常适合人与人之间传递文件档案,但自动化非常尴尬。

回答by Jeff M

zlib isn't meant to open .zip files, but you are in luck: zlib's contrib directory includes minizip, which is able to use zlib to open .zip files.

zlib 并不是要打开 .zip 文件,但你很幸运:zlib 的 contrib 目录包含 minizip,它可以使用 zlib 打开 .zip 文件。

It may not be bundled in the SDK, but you can probably use the bundled version of zlib use it. Grab a copy of the zlib source and look in contrib/minizip.

它可能没有捆绑在 SDK 中,但您可能可以使用捆绑版本的 zlib 使用它。获取 zlib 源代码的副本并查看 contrib/minizip。

回答by SmacL

I haven't used the iPhone, but you may want to look at GZIP, which is a very portable open source zip library available for many platforms.

我没有用过 iPhone,但你可能想看看GZIP,它是一个非常便携的开源 zip 库,可用于许多平台。

回答by James Boston

I had some luck testing this on the iPhone simulator:

我有一些运气在 iPhone 模拟器上测试这个:

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]);       
}

It looks easier than fiddling about with zlib...

看起来比摆弄 zlib 更容易...