c语言zlib压缩解压示例
时间: 2024-11-24 09:17:39 浏览: 43
在C语言中使用zlib库进行文件的压缩和解压,zlib是一个流行的开源数据压缩库,它提供了一系列强大的压缩算法。以下是一个简单的压缩和解压示例:
**压缩示例**:
```c
#include <stdio.h>
#include <zlib.h>
void compress_file(const char *input_filename, const char *output_filename) {
FILE *in = fopen(input_filename, "rb");
if (!in) {
perror("Failed to open input file");
return;
}
FILE *out = fopen(output_filename, "wb");
if (!out) {
perror("Failed to create output file");
fclose(in);
return;
}
uLongf ret;
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
if (ret != Z_OK) {
perror("Deflate initialization failed");
fclose(out);
fclose(in);
return;
}
size_t bytes_read;
unsigned char buffer[4096];
while ((bytes_read = fread(buffer, 1, sizeof(buffer), in)) > 0) {
strm.next_in = buffer;
strm.avail_in = bytes_read;
strm.total_out = 0;
ret = deflate(&strm, Z_FINISH); // 或者 Z_NO_FLUSH for streaming
if (ret == Z_STREAM_END) break; // 如果已经压缩完成
if (ret != Z_OK) {
perror("Deflating data failed");
deflateEnd(&strm);
fclose(out);
fclose(in);
return;
}
size_t bytes_written = strm.total_out;
fwrite(strm.output_buffer, 1, bytes_written, out);
}
deflateEnd(&strm);
fclose(in);
fclose(out);
}
阅读全文