summaryrefslogtreecommitdiffstats
path: root/libzipfile/test_zipfile.c
blob: 1aaa9132d3b711fe6ac05b8af310bdaca20f5ad6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <zipfile/zipfile.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void dump_zipfile(FILE* to, zipfile_t file);

int
main(int argc, char** argv)
{
    FILE* f;
    size_t size, unsize;
    void* buf;
    void* scratch;
    zipfile_t zip;
    zipentry_t entry;
    int err;
    enum { HUH, LIST, UNZIP } what = HUH;

    if (strcmp(argv[2], "-l") == 0 && argc == 3) {
        what = LIST;
    }
    else if (strcmp(argv[2], "-u") == 0 && argc == 5) {
        what = UNZIP;
    }
    else {
        fprintf(stderr, "usage: test_zipfile ZIPFILE -l\n"
                        "          lists the files in the zipfile\n"
                        "       test_zipfile ZIPFILE -u FILENAME SAVETO\n"
                        "          saves FILENAME from the zip file into SAVETO\n");
        return 1;
    }
    
    f = fopen(argv[1], "r");
    if (f == NULL) {
        fprintf(stderr, "couldn't open %s\n", argv[1]);
        return 1;
    }

    fseek(f, 0, SEEK_END);
    size = ftell(f);
    rewind(f);
    
    buf = malloc(size);
    fread(buf, 1, size, f);

    zip = init_zipfile(buf, size);
    if (zip == NULL) {
        fprintf(stderr, "inti_zipfile failed\n");
        return 1;
    }

    fclose(f);


    switch (what)
    {
        case HUH:
            break;
        case LIST:
            dump_zipfile(stdout, zip);
            break;
        case UNZIP:
            entry = lookup_zipentry(zip, argv[3]);
            if (entry == NULL) {
                fprintf(stderr, "zip file '%s' does not contain file '%s'\n",
                                argv[1], argv[1]);
                return 1;
            }
            f = fopen(argv[4], "w");
            if (f == NULL) {
                fprintf(stderr, "can't open file for writing '%s'\n", argv[4]);
                return 1;
            }
            unsize = get_zipentry_size(entry);
            size = unsize * 1.001;
            scratch = malloc(size);
            printf("scratch=%p\n", scratch);
            err = decompress_zipentry(entry, scratch, size);
            if (err != 0) {
                fprintf(stderr, "error decompressing file\n");
                return 1;
            }
            fwrite(scratch, unsize, 1, f);
            free(scratch);
            fclose(f);
            break;
    }
    
    free(buf);

    return 0;
}