91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

C++中gzip壓縮的流程是什么

c++
小樊
81
2024-08-11 11:39:40
欄目: 編程語言

在C++中對數據進行gzip壓縮的流程通常如下:

  1. 包含必要的頭文件:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <zlib.h>
  1. 定義壓縮函數:
std::vector<unsigned char> compress_data(const std::string& data)
{
    z_stream zs;
    memset(&zs, 0, sizeof(zs));

    if (deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY) != Z_OK)
        throw(std::runtime_error("deflateInit2 failed while compressing."));

    zs.next_in = (Bytef*)data.data();
    zs.avail_in = data.size();

    int ret;
    char outbuffer[32768];
    std::vector<unsigned char> outdata;

    do {
        zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
        zs.avail_out = sizeof(outbuffer);

        ret = deflate(&zs, Z_FINISH);

        if (outdata.size() < zs.total_out) {
            outdata.insert(outdata.end(), outbuffer, outbuffer + sizeof(outbuffer) - zs.avail_out);
        }
    } while (zs.avail_out == 0);

    deflateEnd(&zs);

    return outdata;
}
  1. 定義解壓縮函數:
std::string decompress_data(const std::vector<unsigned char>& data)
{
    z_stream zs;
    memset(&zs, 0, sizeof(zs));

    if (inflateInit2(&zs, 16 + MAX_WBITS) != Z_OK)
        throw(std::runtime_error("inflateInit2 failed while decompressing."));

    zs.next_in = (Bytef*)data.data();
    zs.avail_in = data.size();

    int ret;
    char outbuffer[32768];
    std::string outdata;

    do {
        zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
        zs.avail_out = sizeof(outbuffer);

        ret = inflate(&zs, 0);

        if (outdata.size() < zs.total_out) {
            outdata.append(outbuffer, sizeof(outbuffer) - zs.avail_out);
        }
    } while (ret == Z_OK);

    inflateEnd(&zs);

    return outdata;
}
  1. 使用壓縮和解壓縮函數:
int main()
{
    std::string original_data = "This is some test data to compress.";
    std::vector<unsigned char> compressed_data = compress_data(original_data);

    std::string decompressed_data = decompress_data(compressed_data);

    std::cout << "Original Data: " << original_data << std::endl;
    std::cout << "Compressed Data: " << compressed_data.size() << std::endl;
    std::cout << "Decompressed Data: " << decompressed_data << std::endl;

    return 0;
}

以上就是在C++中進行gzip壓縮的基本流程,需要注意使用zlib庫提供的函數來實現壓縮和解壓縮操作。

0
竹北市| 阿合奇县| 麦盖提县| 肃北| 伊春市| 财经| 特克斯县| 饶河县| 吉木萨尔县| 明水县| 弥渡县| 连江县| 南部县| 武川县| 通江县| 基隆市| 莆田市| 沙洋县| 桂阳县| 枣强县| 七台河市| 肥西县| 萍乡市| 九龙坡区| 巧家县| 电白县| 汝阳县| 上思县| 宁波市| 惠东县| 怀安县| 会泽县| 稻城县| 勃利县| 道孚县| 邹平县| 彰化县| 分宜县| 平南县| 隆林| 霍州市|