我可以读取内存中的 zlib 压缩文件而不实际将其解压缩到磁盘吗?如果您能提供一个片段,那就太好了。
最佳答案
这是一个 zLib inflate 例程,它在内存中获取缓冲区并解压缩到提供的输出缓冲区中。这是一个“一次性”函数,因为它会尝试同时膨胀整个输入缓冲区,并假设您已为其提供足够的空间来容纳所有缓冲区。也可以编写一个 multi-shot 函数,根据需要动态增加目标缓冲区。
int inflate(const void *src, int srcLen, void *dst, int dstLen) {
z_stream strm = {0};
strm.total_in = strm.avail_in = srcLen;
strm.total_out = strm.avail_out = dstLen;
strm.next_in = (Bytef *) src;
strm.next_out = (Bytef *) dst;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
int err = -1;
int ret = -1;
err = inflateInit2(&strm, (15 + 32)); //15 window bits, and the +32 tells zlib to to detect if using gzip or zlib
if (err == Z_OK) {
err = inflate(&strm, Z_FINISH);
if (err == Z_STREAM_END) {
ret = strm.total_out;
}
else {
inflateEnd(&strm);
return err;
}
}
else {
inflateEnd(&strm);
return err;
}
inflateEnd(&strm);
return ret;
}
解释:
src:包含压缩(gzip 或 zlib)数据的源缓冲区
srcLen:源缓冲区的长度
dst:目标缓冲区,输出将写入其中
dstLen:目标缓冲区的长度
返回值:
Z_BUF_ERROR:如果 dstLen 不够大,无法容纳膨胀的数据
Z_MEM_ERROR: 如果没有足够的内存来执行解压
Z_DATA_ERROR:如果输入数据损坏
否则,返回值为写入dst的字节数。
关于c - 使用 zlib 进行内存解压,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4901842/