温馨提示×

C++中gzip压缩的流操作有哪些

c++
小樊
95
2024-08-11 11:47:38
栏目: 编程语言

在C++中,可以使用zlib库来进行gzip压缩和解压缩的操作。以下是使用zlib库进行gzip压缩和解压缩的流操作:

  1. 压缩数据流:
#include <zlib.h>

std::string compressData(const std::string& data)
{
    z_stream strm;
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.next_in = (Bytef*)data.data();
    strm.avail_in = data.size();

    if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 | 16, 8, Z_DEFAULT_STRATEGY) != Z_OK)
    {
        return "";
    }

    std::string compressedData;
    char out[1024];

    do
    {
        strm.next_out = (Bytef*)out;
        strm.avail_out = sizeof(out);

        if (deflate(&strm, Z_FINISH) == Z_STREAM_ERROR)
        {
            deflateEnd(&strm);
            return "";
        }

        compressedData.append(out, sizeof(out) - strm.avail_out);
    } while (strm.avail_out == 0);

    deflateEnd(&strm);

    return compressedData;
}

  1. 解压缩数据流:
#include <zlib.h>

std::string decompressData(const std::string& compressedData)
{
    z_stream strm;
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.next_in = (Bytef*)compressedData.data();
    strm.avail_in = compressedData.size();

    if (inflateInit2(&strm, 15 | 16) != Z_OK)
    {
        return "";
    }

    std::string decompressedData;
    char out[1024];

    do
    {
        strm.next_out = (Bytef*)out;
        strm.avail_out = sizeof(out);

        if (inflate(&strm, Z_NO_FLUSH) == Z_STREAM_ERROR)
        {
            inflateEnd(&strm);
            return "";
        }

        decompressedData.append(out, sizeof(out) - strm.avail_out);
    } while (strm.avail_out == 0);

    inflateEnd(&strm);

    return decompressedData;
}

0