]> git.sur5r.net Git - cc65/blob - util/zlib/deflater.c
59ee3f7e5b0c6ef5501331a21e9ed47d30e9119a
[cc65] / util / zlib / deflater.c
1 /*
2  * Compresses data to the DEFLATE format.
3  * The compressed data is ready to use with inflatemem().
4  * Compile using e.g.
5  * gcc -O2 -o deflater deflater.c -lz
6  *
7  * Author: Piotr Fusik <fox@scene.pl>
8  */
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <zlib.h>
12
13 #define IN_SIZE_MAX 60000U
14 #define OUT_SIZE_MAX 60000U
15
16 int main(int argc, char* argv[])
17 {
18         FILE* fp;
19         char* inbuf;
20         char* outbuf;
21         size_t inlen;
22         size_t outlen;
23         z_stream stream;
24
25         /* check command line */
26         if (argc != 3) {
27                 fprintf(stderr,
28                         "Compresses a file to the DEFLATE format.\n"
29                         "24 Aug 2002, Piotr Fusik <fox@scene.pl>\n"
30                         "Usage: deflater input_file deflated_file\n"
31                 );
32                 return 3;
33         }
34
35         /* alloc buffers */
36         inbuf = malloc(IN_SIZE_MAX);
37         outbuf = malloc(OUT_SIZE_MAX);
38         if (inbuf == NULL || outbuf == NULL) {
39                 fprintf(stderr, "deflater: Out of memory!\n");
40                 return 1;
41         }
42
43         /* read input file */
44         fp = fopen(argv[1], "rb");
45         if (fp == NULL) {
46                 perror(argv[1]);
47                 return 1;
48         }
49         inlen = fread(inbuf, 1, IN_SIZE_MAX, fp);
50         fclose(fp);
51
52         /* compress */
53         stream.next_in = inbuf;
54         stream.avail_in = inlen;
55         stream.next_out = outbuf;
56         stream.avail_out = OUT_SIZE_MAX;
57         stream.zalloc = (alloc_func) 0;
58         stream.zfree = (free_func) 0;
59         if (deflateInit2(&stream, Z_BEST_COMPRESSION, Z_DEFLATED,
60                 -MAX_WBITS, 9, Z_DEFAULT_STRATEGY) != Z_OK) {
61                 fprintf(stderr, "deflater: deflateInit2 failed\n");
62                 return 1;
63         }
64         if (deflate(&stream, Z_FINISH) != Z_STREAM_END) {
65                 fprintf(stderr, "deflater: deflate failed\n");
66                 return 1;
67         }
68         if (deflateEnd(&stream) != Z_OK) {
69                 fprintf(stderr, "deflater: deflateEnd failed\n");
70                 return 1;
71         }
72
73         /* write output */
74         fp = fopen(argv[2], "wb");
75         if (fp == NULL) {
76                 perror(argv[2]);
77                 return 1;
78         }
79         outlen = fwrite(outbuf, 1, stream.total_out, fp);
80         fclose(fp);
81         if (outlen != stream.total_out) {
82                 perror(argv[2]);
83                 return 1;
84         }
85
86         /* display summary */
87         printf("Compressed %s (%d bytes) to %s (%d bytes)\n",
88                 argv[1], inlen, argv[2], outlen);
89         return 0;
90 }