c++ zlib库的使用
时间: 2023-06-24 16:04:54 浏览: 200
zlib是一个用于压缩和解压缩数据的开源库,它常于将文件或网络传输的数据进行压缩,以减少传输时间和网络流量。
下面是使用zlib库进行压缩和解压缩的示例代码:
压缩:
```c++
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstring>
#include "zlib.h"
bool compress(const std::string& in_file, const std::string& out_file)
{
std::ifstream fin(in_file, std::ios::binary);
if (!fin) {
std::cerr << "Failed to open input file: " << in_file << std::endl;
return false;
}
std::ofstream fout(out_file, std::ios::binary);
if (!fout) {
std::cerr << "Failed to open output file: " << out_file << std::endl;
return false;
}
const int BUF_SIZE = 1024 * 8;
char in_buf[BUF_SIZE];
char out_buf[BUF_SIZE];
z_stream zs;
memset(&zs, 0, sizeof(zs));
if (deflateInit(&zs, Z_DEFAULT_COMPRESSION) != Z_OK) {
std::cerr << "Failed to initialize zlib compression" << std::endl;
return false;
}
while (true) {
fin.read(in_buf, BUF_SIZE);
std::streamsize bytes_in = fin.gcount();
if (bytes_in == 0) {
break;
}
zs.next_in = reinterpret_cast<Bytef*>(in_buf);
zs.avail_in = static_cast<uInt>(bytes_in);
do {
zs.next_out = reinterpret_cast<Bytef*>(out_buf);
zs.avail_out = BUF_SIZE;
int ret = deflate(&zs, Z_FINISH);
if (ret == Z_STREAM_ERROR) {
std::cerr << "Failed to compress input data" << std::endl;
deflateEnd(&zs);
return false;
}
std::streamsize bytes_out = BUF_SIZE - zs.avail_out;
fout.write(out_buf, bytes_out);
} while (zs.avail_out == 0);
}
deflateEnd(&zs);
return true;
}
```
解压缩:
```c++
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstring>
#include "zlib.h"
bool decompress(const std::string& in_file, const std::string& out_file)
{
std::ifstream fin(in_file, std::ios::binary);
if (!fin) {
std::cerr << "Failed to open input file: " << in_file << std::endl;
return false;
}
std::ofstream fout(out_file, std::ios::binary);
if (!fout) {
std::cerr << "Failed to open output file: " << out_file << std::endl;
return false;
}
const int BUF_SIZE = 1024 * 8;
char in_buf[BUF_SIZE];
char out_buf[BUF_SIZE];
z_stream zs;
memset(&zs, 0, sizeof(zs));
if (inflateInit(&zs) != Z_OK) {
std::cerr << "Failed to initialize zlib decompression" << std::endl;
return false;
}
while (true) {
fin.read(in_buf, BUF_SIZE);
std::streamsize bytes_in = fin.gcount();
if (bytes_in == 0) {
break;
}
zs.next_in = reinterpret_cast<Bytef*>(in_buf);
zs.avail_in = static_cast<uInt>(bytes_in);
do {
zs.next_out = reinterpret_cast<Bytef*>(out_buf);
zs.avail_out = BUF_SIZE;
int ret = inflate(&zs, Z_NO_FLUSH);
if (ret == Z_STREAM_ERROR) {
std::cerr << "Failed to decompress input data" << std::endl;
inflateEnd(&zs);
return false;
}
std::streamsize bytes_out = BUF_SIZE - zs.avail_out;
fout.write(out_buf, bytes_out);
} while (zs.avail_out == 0);
}
inflateEnd(&zs);
return true;
}
```
在上述代码中,使用了z_stream结构体来保存压缩或解压缩的状态信息,其中deflateInit和inflateInit函数用于初始化z_stream结构体,deflate和inflate函数用于执行压缩和解压缩操作,deflateEnd和inflateEnd函数用于释放相关资源。
需要注意的是,压缩和解压缩的数据均应该是二进制数据,因此在打开文件时需要指定std::ios::binary标志。
阅读全文