#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <fstream>
#include <zlib.h>
static bool gzip_compress(const std::string &original_str, std::string &str) {
z_stream d_stream = { 0 };
if (Z_OK != deflateInit2(&d_stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, MAX_WBITS + 16, 9, Z_DEFAULT_STRATEGY)) {
return false;
}
uLong len = compressBound(original_str.size());
unsigned char *buf = (unsigned char*)malloc(len);
if (!buf) {
return false;
}
d_stream.next_in = (unsigned char *)(original_str.c_str());
d_stream.avail_in = original_str.size();
d_stream.next_out = buf;
d_stream.avail_out = len;
deflate(&d_stream, Z_SYNC_FLUSH);
deflateEnd(&d_stream);
str.assign((char *)buf, d_stream.total_out);
free(buf);
return true;
}
static void gzip_uncompress(const std::string &original_str,
zlib压缩解压缩字符串为gzip格式
最新推荐文章于 2023-08-24 17:40:35 发布
本文介绍了一种使用GZIP算法进行数据压缩和解压缩的方法。通过C++代码实现,展示了如何使用zlib库来压缩字符串数据,并将其解压缩回原始状态。文章包括了压缩和解压缩的完整代码示例,以及如何测量压缩比。

最低0.47元/天 解锁文章
578





