压缩http协议的c语言代码

#由于刚毕业最近开始上班,所以从今天开始写一些工作中遇到的问题的一些代码#

使用zlib工具压缩

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>

#define CHUNK 16384

int deflate_compress(const char *data, int data_len, char **compressed_data, int *compressed_len) {
    z_stream strm;
    int ret;
    int flush;
    unsigned have;
    char out[CHUNK];

    *compressed_data = NULL;
    *compressed_len = 0;

    /* allocate deflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    ret = deflateInit(&strm, Z_DEFAULT_COMPRESSION);
    if (ret != Z_OK)
        return ret;

    strm.avail_in = data_len;
    strm.next_in = (Bytef *)data;

    do {
        strm.avail_out = CHUNK;
        strm.next_out = (Bytef *)out;
        flush = (strm.avail_in == 0) ? Z_FINISH : Z_NO_FLUSH;
        ret = deflate(&strm, flush);    /* no bad return value */
        if (ret == Z_STREAM_ERROR) {
            deflateEnd(&strm);
            return ret;
        }
        have = CHUNK - strm.avail_out;
        *compressed_data = realloc(*compressed_data, *compressed_len + have);
        if (*compressed_data == NULL) {
            deflateEnd(&strm);
            return Z_MEM_ERROR;
        }
        memcpy(*compressed_data + *compressed_len, out, have);
        *compressed_len += have;
    } while (strm.avail_out == 0);

    /* clean up and return */
    deflateEnd(&strm);
    return Z_OK;
}

int main() {
    const char *data = "This is some test data to compress using deflate algorithm.";
    int data_len = strlen(data);
    char *compressed_data;
    int compressed_len;

    int ret = deflate_compress(data, data_len, &compressed_data, &compressed_len);
    if (ret == Z_OK) {
        printf("Original data length: %d\n", data_len);
        printf("Compressed data length: %d\n", compressed_len);
        printf("Compressed data: %s\n", compressed_data); // Just for demonstration, not recommended to print compressed data as string
        free(compressed_data);
    } else {
        fprintf(stderr, "Compression failed with error code %d\n", ret);
    }

    return 0;
}

 

  • 16
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值