我正在尝试使用 zlib 库读取 test.zip 文件并提取内容。我的要求是先读取每个文件并将内容(解压缩)输出到内存,然后再输出到文件。
我尝试了下面的代码:
#include <iostream>
#include <zlib.h>
using namespace std;
#define LINE 1024
int main()
{
const char *filename = "hello.zip";
gzFile inFileZ = gzopen(filename, "rb");
if (inFileZ == NULL) {
printf("Error: Failed to gzopen %s\n", filename);
return -1;
}
unsigned char unzipBuffer[8192];
unsigned int unzippedBytes;
std::vector<unsigned char> unzippedData;
while (true) {
unzippedBytes = gzread(inFileZ, unzipBuffer, 8192);
if (unzippedBytes > 0) {
cout << unzippedBytes << endl;
for (int i = 0; i < unzippedBytes; i++) {
cout << unzipBuffer[i];
}
} else {
break;
}
}
gzclose(inFileZ);
return 0;
}
我从网上得到了上面的例子。有人提到 gzread
会膨胀内容并填充缓冲区(这里是 unzipBuffer
)。但是,当我尝试打印它时,它打印的是 .zip 文件的相同内容(例如 PK.....
代码不可读)。
我相信我没有正确使用 zlib 的 API。但是我找不到与此相关的示例。有人可以帮我吗?
最佳答案
zlib 库不直接处理 zip 格式。 zlib 提供处理压缩压缩条目所需的原始压缩和解压缩,以及 CRC-32 计算工具。但是,您需要编写自己的代码或使用其他库来解析和处理 zip 格式。
gzip 不是 zip。它们是两种完全不同的格式,它们使用或可能使用相同的原始压缩格式。
关于c++ - 将 zlib 与 mingw 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30648870/