home *** CD-ROM | disk | FTP | other *** search
/ Syzygy Magazine 8 / Syzygy_Magazine_8_2002___pl_Disk_1_of_2_Side_B_B.atr / deflater.zip / deflater.c next >
C/C++ Source or Header  |  2002-08-24  |  2KB  |  83 lines

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