#由于刚毕业最近开始上班,所以从今天开始写一些工作中遇到的问题的一些代码#
使用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;
}