|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | +#include <string> |
| 4 | +#include <assert.h> |
| 5 | +#include "zlib.h" |
| 6 | +#define CHUNK 16384 |
| 7 | + |
| 8 | +int main(int argc, const char** argv) { |
| 9 | + if(argc != 3) { |
| 10 | + printf("Usage: extractcrash <input> <output>\n"); |
| 11 | + return 0; |
| 12 | + } |
| 13 | + FILE* source = fopen(argv[1], "rb"); |
| 14 | + FILE* dest = fopen(argv[2], "wb"); |
| 15 | + |
| 16 | + unsigned char in[CHUNK]; |
| 17 | + unsigned char out[CHUNK]; |
| 18 | + unsigned have; |
| 19 | + z_stream strm; |
| 20 | + |
| 21 | + strm.zalloc = Z_NULL; |
| 22 | + strm.zfree = Z_NULL; |
| 23 | + strm.opaque = Z_NULL; |
| 24 | + strm.avail_in = 0; // size of input |
| 25 | + strm.next_in = Z_NULL; // input char array |
| 26 | + |
| 27 | + // the actual DE-compression work. |
| 28 | + int ret = inflateInit(&strm); |
| 29 | + if (ret != Z_OK) { |
| 30 | + printf("Decompress failed! %d\n", ret); |
| 31 | + return ret; |
| 32 | + } |
| 33 | + |
| 34 | + /* decompress until deflate stream ends or end of file */ |
| 35 | + do { |
| 36 | + strm.avail_in = fread(in, 1, CHUNK, source); |
| 37 | + |
| 38 | + if (ferror(source)) { |
| 39 | + (void)inflateEnd(&strm); |
| 40 | + return Z_ERRNO; |
| 41 | + } |
| 42 | + |
| 43 | + if (strm.avail_in == 0) |
| 44 | + break; |
| 45 | + |
| 46 | + strm.next_in = in; |
| 47 | + |
| 48 | + /* run inflate() on input until output buffer not full */ |
| 49 | + do { |
| 50 | + strm.avail_out = CHUNK; |
| 51 | + strm.next_out = out; |
| 52 | + ret = inflate(&strm, Z_NO_FLUSH); |
| 53 | + assert(ret != Z_STREAM_ERROR); /* state not clobbered */ |
| 54 | + switch (ret) { |
| 55 | + case Z_NEED_DICT: |
| 56 | + ret = Z_DATA_ERROR; /* and fall through */ |
| 57 | + case Z_DATA_ERROR: |
| 58 | + case Z_MEM_ERROR: |
| 59 | + (void)inflateEnd(&strm); |
| 60 | + return ret; |
| 61 | + } |
| 62 | + |
| 63 | + have = CHUNK - strm.avail_out; |
| 64 | + |
| 65 | + if (fwrite(out, 1, have, dest) != have || ferror(dest)) { |
| 66 | + (void)inflateEnd(&strm); |
| 67 | + return Z_ERRNO; |
| 68 | + } |
| 69 | + } while (strm.avail_out == 0); |
| 70 | + |
| 71 | + /* done when inflate() says it's done */ |
| 72 | + } while (ret != Z_STREAM_END); |
| 73 | + |
| 74 | + /* clean up and return */ |
| 75 | + (void)inflateEnd(&strm); |
| 76 | + |
| 77 | + return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; |
| 78 | + |
| 79 | + return 0; |
| 80 | +} |
0 commit comments