| 1 | /* |
| 2 | * :make compdecomp CFLAGS=-Wall LDFLAGS=-lz |
| 3 | */ |
| 4 | #include <stdio.h> |
| 5 | #include <stdlib.h> |
| 6 | #include <zlib.h> |
| 7 | |
| 8 | #define MEM_LIMIT (128*1024*1024) |
| 9 | |
| 10 | int main(int argc, char *argv[]) |
| 11 | { |
| 12 | void *pi, *po = NULL; |
| 13 | FILE *fi, *fo; |
| 14 | int ret, si, so; |
| 15 | |
| 16 | if (argc != 4) |
| 17 | { |
| 18 | printf("usage: %s <0|1> <infile> <outfile>\n", argv[0]); |
| 19 | return 1; |
| 20 | } |
| 21 | |
| 22 | fi = fopen(argv[2], "rb"); |
| 23 | if (fi == NULL) return 2; |
| 24 | |
| 25 | fseek(fi, 0, SEEK_END); |
| 26 | si = ftell(fi); |
| 27 | fseek(fi, 0, SEEK_SET); |
| 28 | pi = malloc(si); |
| 29 | if (pi == NULL) return 3; |
| 30 | fread(pi, 1, si, fi); |
| 31 | fclose(fi); |
| 32 | |
| 33 | if (atoi(argv[1])) |
| 34 | { |
| 35 | // decompress |
| 36 | so = si; |
| 37 | do |
| 38 | { |
| 39 | so *= 16; |
| 40 | if (so > MEM_LIMIT) return 4; |
| 41 | po = realloc(po, so); |
| 42 | if (po == NULL) return 5; |
| 43 | ret = uncompress(po, (uLongf *) &so, pi, si); |
| 44 | } |
| 45 | while (ret == Z_BUF_ERROR); |
| 46 | } |
| 47 | else |
| 48 | { |
| 49 | // compress |
| 50 | so = si + 1024; |
| 51 | po = malloc(so); |
| 52 | if (po == NULL) return 5; |
| 53 | ret = compress2(po, (uLongf *) &so, pi, si, Z_BEST_COMPRESSION); |
| 54 | } |
| 55 | |
| 56 | if (ret == Z_OK) |
| 57 | { |
| 58 | fo = fopen(argv[3], "wb"); |
| 59 | if (fo == NULL) return 6; |
| 60 | fwrite(po, 1, so, fo); |
| 61 | fclose(fo); |
| 62 | } |
| 63 | |
| 64 | printf("result %i, size %i -> %i\n", ret, si, so); |
| 65 | |
| 66 | return ret; |
| 67 | } |
| 68 | |