用c++写一个压缩软件
时间: 2023-05-22 21:01:09 浏览: 76
好的,压缩软件可以使用 zlib 库来实现。以下是一个简单的压缩程序的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#define CHUNK_SIZE 16384
int compress_file(const char *source, const char *dest) {
FILE *src_file = fopen(source, "rb");
if (!src_file) {
printf("Failed to open source file.\n");
return -1;
}
FILE *dst_file = fopen(dest, "wb");
if (!dst_file) {
printf("Failed to open destination file.\n");
fclose(src_file);
return -1;
}
z_stream stream;
memset(&stream, 0, sizeof(stream));
deflateInit(&stream, Z_DEFAULT_COMPRESSION);
unsigned char in_buf[CHUNK_SIZE];
unsigned char out_buf[CHUNK_SIZE];
int ret;
do {
stream.avail_in = fread(in_buf, 1, CHUNK_SIZE, src_file);
if (ferror(src_file)) {
printf("Failed to read from source file.\n");
ret = -1;
break;
}
stream.next_in = in_buf;
do {
stream.avail_out = CHUNK_SIZE;
stream.next_out = out_buf;
ret = deflate(&stream, feof(src_file) ? Z_FINISH : Z_NO_FLUSH);
if (ret == Z_STREAM_ERROR) {
printf("Failed to compress data.\n");
ret = -1;
break;
}
fwrite(out_buf, 1, CHUNK_SIZE - stream.avail_out, dst_file);
} while (stream.avail_out == 0);
if (ret != Z_OK) {
break;
}
} while (!feof(src_file));
deflateEnd(&stream);
fclose(src_file);
fclose(dst_file);
return ret == Z_STREAM_END ? 0 : -1;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <source file> <destination file>\n", argv[0]);
return -1;
}
int ret = compress_file(argv[1], argv[2]);
if (ret != 0) {
printf("Failed to compress file.\n");
return -1;
}
printf("File compressed successfully.\n");
return 0;
}
```
这个程序使用 zlib 库中的 deflate 函数来压缩文件。它将源文件分成大小为 CHUNK_SIZE 的块,并将每个块压缩到输出缓冲区中。输出缓冲区的内容被写入目标文件中。