This repository has been archived by the owner on Nov 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
compress.c
91 lines (82 loc) · 1.9 KB
/
compress.c
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
#include "compress.h"
#include <zlib.h>
#include <stdio.h>
int zdeflate(FILE *source, FILE *dest, int level)
{
int ret, flush;
unsigned int have;
z_stream stream;
unsigned char in[CHUNK];
unsigned char out[CHUNK];
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
if ((ret = deflateInit(&stream, level)) != Z_OK)
return ret;
do {
stream.avail_in = fread(in, 1, CHUNK, source);
if (ferror(source)) {
deflateEnd(&stream);
return Z_ERRNO;
}
flush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
stream.next_in = in;
do {
stream.avail_out = CHUNK;
stream.next_out = out;
ret = deflate(&stream, flush);
have = CHUNK - stream.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
deflateEnd(&stream);
return Z_ERRNO;
}
} while (!stream.avail_out);
} while (flush != Z_FINISH);
deflateEnd(&stream);
return Z_OK;
}
int zinflate(FILE *source, FILE *dest)
{
int ret;
unsigned int have;
z_stream stream;
unsigned char in[CHUNK];
unsigned char out[CHUNK];
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
stream.avail_in = 0;
stream.next_in = Z_NULL;
if ((ret = inflateInit(&stream)) != Z_OK)
return ret;
do {
stream.avail_in = fread(in, 1, CHUNK, source);
if (ferror(source)) {
inflateEnd(&stream);
return Z_ERRNO;
}
if (!stream.avail_in)
break;
stream.next_in = in;
do {
stream.avail_out = CHUNK;
stream.next_out = out;
ret = inflate(&stream, Z_NO_FLUSH);
switch (ret) {
case Z_NEED_DICT:
ret = Z_DATA_ERROR;
case Z_DATA_ERROR:
case Z_MEM_ERROR:
inflateEnd(&stream);
return ret;
}
have = CHUNK - stream.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
inflateEnd(&stream);
return Z_ERRNO;
}
} while (!stream.avail_out);
} while (ret != Z_STREAM_END);
inflateEnd(&stream);
return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}