zlib iPhone - 文件开始变废话

时间:2009-10-19 14:06:18

标签: iphone compression zlib

我的捆绑包中有几个.tgz文件,我想要解压缩并写入文件。我有它的工作 - 有点。问题是写入的文件前面有512字节的垃圾数据,但除此之外,该文件已成功解压缩。

alt text
(来源:pici.se

我不想要废话。如果它总是512字节,那么当然很容易跳过那些并写下其他的。但它总是这样吗?如果不知道为什么那些字节在那里,那么冒险做类似的事情。

    gzFile f = gzopen ([[[NSBundle mainBundle] pathForResource:file ofType:@"tgz"] cStringUsingEncoding:NSASCIIStringEncoding], [@"rb" cStringUsingEncoding:NSASCIIStringEncoding]); 
    unsigned int length = 1024*1024;
    void *buffer = malloc(length);
    NSMutableData *data = [NSMutableData new];

    while (true)
    {   
        int read = gzread(f, buffer, length);

        if (read > 0)
        {
            [data appendBytes:buffer length:read];
        }
        else if (read == 0)
            break;
        else if (read == -1)
        {
            throw [NSException exceptionWithName:@"Decompression failed" reason:@"read = -1" userInfo:nil];
        }
        else
        {
            throw [NSException exceptionWithName:@"Unexpected state from zlib" reason:@"read < -1" userInfo:nil];
        }
    }

    int writeSucceeded = [data writeToFile:file automatically:YES];

    free(buffer);
    [data release];

    if (!writeSucceeded)
        throw [NSException exceptionWithName:@"Write failed" reason:@"writeSucceeded != true" userInfo:nil];

2 个答案:

答案 0 :(得分:6)

根据您发布的代码,您似乎只是尝试使用gzip读取Tar'ed gZip的文件。

我的猜测是解压缩后文件开头的“垃圾”实际上就是TAR文件头(我在开头就看到了一个文件名)。

Tar File Format处的更多提示指向512字节大小。

gzip只能压缩单个文件。如果您只是尝试压缩单个文件,则不需要首先对它进行tar。

如果您尝试压缩多个文件并作为单个存档,则需要使用TAR并在解压缩后解压缩文件。

只是一个猜测。

克里斯。

答案 1 :(得分:1)

这看起来像是一个合理的实施。您是否尝试使用已知的好工具(即tar -xzf)解压缩TGZ并查看其是否正常?