我的包中有几个 .tgz 文件,我想解压缩并写入文件。我已经让它工作了 - 有点。问题是写入的文件前面有512字节的垃圾数据,但除此之外,文件解压缩成功。
(来源: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];