quano
quano

Reputation: 19112

zlib iPhone - files get crap in beginning

I've got a couple of .tgz-files in my bundle that I want to uncompress and write to file. I've got it working - sort of. The problem is that the file written gets 512 bytes of crap data in front of it, but other than that, the file is uncompressed successfully.

alt text
(source: pici.se)

I don't want the crap. If it's always 512 bytes, it is of course easy to just skip those and write the others. But is it always like that? Risky to do something like that if one does not know why those bytes are there in the first place.

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

Upvotes: 2

Views: 827

Answers (2)

PyjamaSam
PyjamaSam

Reputation: 10425

Based on the code you posted it looks like your trying to read a Tar'ed gZip'ed file using gzip only.

My guess is that the "junk" at the start of the file after decompression is infact the TAR file header (I see a file name there right at the start).

More hints at Tar File Format point to the 512 byte size.

gzip can only compress a single file. If you are only trying to compress a single file you don't need to tar it first.

If you are trying to compress multiple files and as a single archive then you would need to use TAR and untar the files after you decompressed them.

Just a guess.

chris.

Upvotes: 6

Adam Wright
Adam Wright

Reputation: 49376

It looks like a reasonable implementation. Have you tried decompressing the TGZ with a known good tool (i.e. tar -xzf) and seeing if that works OK?

Upvotes: 1

Related Questions