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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "zlib.h"
/*--------------------------------------------------------------------------
compression
-------------------------------------------------------------------------*/
/* ------------------------------------------------------------------------ *
* deflate : compression d'un fichier
*
*
* ------------------------------------------------------------------------ */
/**
* @brief
* Compression d'un fichier
*
* @param str_src - fichier d'entrée à compresser
* @param str_dest - fichier de sortie compressé
* @param level - taux de compression
*
* @return
* Succès : Z_OK, sinon code erreur ZLIB
*
*/
int deflate(char* str_src, char* str_dest, int level)
{
FILE *source;
FILE *dest;
int ret, flush;
unsigned have;
z_stream strm;
char in[CHUNK];
char out[CHUNK];
source = fopen(str_src, "rb");
dest = fopen(str_dest, "wb");
/* allocate deflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = deflateInit(&strm, level);
if (ret != Z_OK)
return ret;
/* compress until end of file */
do
{
strm.avail_in = fread(in, 1, CHUNK, source);
if (ferror(source))
{
deflateEnd(&strm);
fclose(source);
fclose(dest);
return Z_ERRNO;
}
flush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
strm.next_in = (Bytef*)in;
/* run deflate() on input until output buffer not full, finish
compression if all of source has been read in */
do
{
strm.avail_out = CHUNK;
strm.next_out = (Bytef*) out;
ret = deflate(&strm, flush); /* no bad return value */
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
have = CHUNK - strm.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror(dest))
{
deflateEnd(&strm);
fclose(source);
fclose(dest);
return Z_ERRNO;
}
}
while (strm.avail_out == 0);
assert(strm.avail_in == 0); /* all input will be used */
/* done when last data in file processed */
}
while (flush != Z_FINISH);
assert(ret == Z_STREAM_END); /* stream will be complete */
/* clean up and return */
deflateEnd(&strm);
fclose(source);
fclose(dest);
return Z_OK;
} |
Partager