admin 管理员组文章数量: 1086019
2024年3月13日发(作者:linux系统安装教程全版学习)
c++压缩实例
在 C++ 中,常见的压缩和解压缩库有 zlib、gzip、zstd 等。下面是一个使用 zlib 进行压缩
和解压缩的简单示例。请注意,为了运行这个示例,你需要安装 zlib 库,并在编译时链接 zlib
库。
```cpp
#include
#include
#include
// 压缩函数
std::string compress(const std::string& data) {
z_stream zs; // zlib 的数据结构
memset(&zs, 0, sizeof(zs));
if (deflateInit(&zs, Z_BEST_COMPRESSION) != Z_OK) {
throw std::runtime_error("deflateInit failed while compressing.");
}
_in = (Bytef*)();
_in = ();
int ret;
char outbuffer[32768];
std::string outstring;
do {
_out = reinterpret_cast
_out = sizeof(outbuffer);
ret = deflate(&zs, Z_FINISH);
if (() < _out) {
(outbuffer, _out - ());
}
} while (ret == Z_OK);
deflateEnd(&zs);
if (ret != Z_STREAM_END) {
throw std::runtime_error("Exception during zlib compression: (" + std::to_string(ret) +
")");
}
return outstring;
}
// 解压函数
std::string decompress(const std::string& compressed) {
z_stream zs;
memset(&zs, 0, sizeof(zs));
if (inflateInit(&zs) != Z_OK) {
throw std::runtime_error("inflateInit failed while decompressing.");
}
_in = (Bytef*)();
_in = ();
int ret;
char outbuffer[32768];
std::string outstring;
do {
_out = reinterpret_cast
_out = sizeof(outbuffer);
ret = inflate(&zs, 0);
if (() < _out) {
(outbuffer, _out - ());
}
} while (ret == Z_OK);
inflateEnd(&zs);
if (ret != Z_STREAM_END) {
throw std::runtime_error("Exception during zlib decompression: (" + std::to_string(ret)
+ ")");
}
return outstring;
}
int main() {
std::string originalData = "Hello, this is a sample string for compression and
decompression.";
std::string compressedData = compress(originalData);
std::cout << "Compressed data: " << compressedData << std::endl;
std::string decompressedData = decompress(compressedData);
std::cout << "Decompressed data: " << decompressedData << std::endl;
return 0;
}
```
这个例子中使用了 zlib 库进行压缩和解压缩。请确保在你的环境中安装了 zlib 库,并在编
译时链接该库。这只是一个简单的示例,实际使用中可能需要更多的错误处理和边界检查。
版权声明:本文标题:c++压缩实例 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1710316550a567600.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论