C++ zlib使用
时间: 2024-06-06 18:02:25 浏览: 213
C++中使用zlib库可以实现数据的压缩和解压缩。下面是一个简单的示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <zlib.h>
// 压缩函数
bool compressFile(const std::string& sourceFile, const std::string& destFile) {
std::ifstream inFile(sourceFile, std::ios::binary);
std::ofstream outFile(destFile, std::ios::binary);
if (!inFile || !outFile) {
return false;
}
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
if (deflateInit(&stream, Z_DEFAULT_COMPRESSION) != Z_OK) {
return false;
}
char inBuffer[1024];
char outBuffer[1024];
stream.avail_in = inFile.readsome(inBuffer, sizeof(inBuffer));
stream.next_in = reinterpret_cast<Bytef*>(inBuffer);
do {
stream.avail_out = sizeof(outBuffer);
stream.next_out = reinterpret_cast<Bytef*>(outBuffer);
deflate(&stream, Z_FINISH);
outFile.write(outBuffer, sizeof(outBuffer) - stream.avail_out);
} while (stream.avail_out == 0);
deflateEnd(&stream);
inFile.close();
outFile.close();
return true;
}
// 解压缩函数
bool decompressFile(const std::string& sourceFile, const std::string& destFile) {
std::ifstream inFile(sourceFile, std::ios::binary);
std::ofstream outFile(destFile, std::ios::binary);
if (!inFile || !outFile) {
return false;
}
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
if (inflateInit(&stream) != Z_OK) {
return false;
}
char inBuffer[1024];
char outBuffer[1024];
stream.avail_in = inFile.readsome(inBuffer, sizeof(inBuffer));
stream.next_in = reinterpret_cast<Bytef*>(inBuffer);
do {
stream.avail_out = sizeof(outBuffer);
stream.next_out = reinterpret_cast<Bytef*>(outBuffer);
inflate(&stream, Z_NO_FLUSH);
outFile.write(outBuffer, sizeof(outBuffer) - stream.avail_out);
} while (stream.avail_out == 0);
inflateEnd(&stream);
inFile.close();
outFile.close();
return true;
}
int main() {
std::string sourceFile = "input.txt";
std::string compressedFile = "compressed.zlib";
std::string decompressedFile = "decompressed.txt";
// 压缩文件
if (compressFile(sourceFile, compressedFile)) {
std::cout << "File compressed successfully." << std::endl;
} else {
std::cout << "Failed to compress file." << std::endl;
}
// 解压缩文件
if (decompressFile(compressedFile, decompressedFile)) {
std::cout << "File decompressed successfully." << std::endl;
} else {
std::cout << "Failed to decompress file." << std::endl;
}
return 0;
}
```
这个示例代码演示了如何使用zlib库进行文件的压缩和解压缩。你可以根据自己的需求修改输入输出文件的路径和名称。在压缩文件时,使用`deflate`函数将输入数据压缩,并将压缩后的数据写入输出文件。在解压缩文件时,使用`inflate`函数将压缩数据解压缩,并将解压缩后的数据写入输出文件。
阅读全文