当我们使用字典时,我试图理解原始放气的功能。我知道以下内容。1.当我们使用字典时,应用程序应该为放气()和膨胀()提供相同的字典。2.当进行原始放气时,必须在任何放气调用之前或在完成放气块后立即调用此函数,即在使用任何刷新选项Z_BLOCK
、Z_PARTIAL_FLUSH
、Z_SYNC_FLUSH
或Z_FULL_FLUSH
时,在所有输入都被消耗并且所有输出都已交付之后。(来自zlib文档)。
但是下面的应用程序无法解压之前使用相同应用程序压缩的内容。压缩和解压缩成功,但输入和未压缩文件不匹配。
放气:
do {
ret = deflateSetDictionary(&strm, dictionary, sizeof(dictionary));
if(ret != Z_OK) {
fprintf(stderr, "Failed to set deflate dictionary\n");
return Z_STREAM_ERROR;
}
strm.avail_in = fread(in, 1, CHUNK, source);
if (ferror(source)) {
(void)deflateEnd(&strm);
return Z_ERRNO;
}
flush = feof(source) ? Z_FINISH : Z_FULL_FLUSH;
strm.next_in = 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 = 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)) {
(void)deflateEnd(&strm);
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);
充气:
do {
ret = inflateSetDictionary(&strm, dictionary, sizeof(dictionary));
if(ret != Z_OK) {
fprintf(stderr, "Failed to set inflate dictionary\n");
return Z_STREAM_ERROR;
}
strm.avail_in = fread(in, 1, CHUNK, source);
if (ferror(source)) {
(void)inflateEnd(&strm);
return Z_ERRNO;
}
if (strm.avail_in == 0)
break;
strm.next_in = in;
/* run inflate() on input until output buffer not full */
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = inflate(&strm, Z_FULL_FLUSH);
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
switch (ret) {
case Z_NEED_DICT:
ret = Z_DATA_ERROR; /* and fall through */
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
return ret;
}
have = CHUNK - strm.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
(void)inflateEnd(&strm);
return Z_ERRNO;
}
} while (strm.avail_out == 0);
/* done when inflate() says it's done */
} while (ret != Z_STREAM_END);
收缩时,每输入一个CHUNK
字节就设置一个相同的字典。为什么?您应该在deflateInit2()
之后使用deflateSetDictionary()
一次。从那时起,输入数据本身应该比您可能提供的字典更好地作为匹配字符串的来源。
在膨胀方面,您必须知道压缩块的结束位置,以便您可以在压缩时发生的完全相同的位置执行 inflateSetDictionary()。
这将需要某种标记、计数或搜索完整的刷新模式。