在C語言中,可以使用zlib庫來進(jìn)行文件的壓縮和解壓縮操作。以下是一個簡單的示例代碼,演示如何使用zlib庫來壓縮一個文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#define CHUNK 16384
int compress_file(const char *source, const char *dest) {
FILE *source_file = fopen(source, "rb");
if (!source_file) {
fprintf(stderr, "Unable to open source file\n");
return -1;
}
FILE *dest_file = fopen(dest, "wb");
if (!dest_file) {
fprintf(stderr, "Unable to open destination file\n");
fclose(source_file);
return -1;
}
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
stream.avail_in = 0;
stream.next_in = Z_NULL;
if (deflateInit(&stream, Z_BEST_COMPRESSION) != Z_OK) {
fprintf(stderr, "Failed to initialize deflate stream\n");
fclose(source_file);
fclose(dest_file);
return -1;
}
unsigned char in[CHUNK];
unsigned char out[CHUNK];
int ret;
do {
stream.avail_in = fread(in, 1, CHUNK, source_file);
if (ferror(source_file)) {
deflateEnd(&stream);
fclose(source_file);
fclose(dest_file);
return -1;
}
stream.next_in = in;
do {
stream.avail_out = CHUNK;
stream.next_out = out;
ret = deflate(&stream, feof(source_file) ? Z_FINISH : Z_NO_FLUSH);
if (ret == Z_STREAM_ERROR) {
deflateEnd(&stream);
fclose(source_file);
fclose(dest_file);
return -1;
}
fwrite(out, 1, CHUNK - stream.avail_out, dest_file);
} while (stream.avail_out == 0);
} while (!feof(source_file);
deflateEnd(&stream);
fclose(source_file);
fclose(dest_file);
return 0;
}
int main() {
const char *source_file = "source.txt";
const char *dest_file = "compressed.dat";
if (compress_file(source_file, dest_file) == 0) {
printf("File compressed successfully\n");
} else {
printf("Failed to compress file\n");
}
return 0;
}
在上面的代碼中,compress_file
函數(shù)用于壓縮一個文件。首先打開源文件和目標(biāo)文件,然后使用zlib庫中的deflateInit
函數(shù)初始化壓縮流。接著循環(huán)讀取源文件數(shù)據(jù),并使用deflate
函數(shù)將數(shù)據(jù)進(jìn)行壓縮,最后將壓縮后的數(shù)據(jù)寫入目標(biāo)文件。壓縮完成后,關(guān)閉文件和釋放資源。
注意:在編譯這段代碼之前,需要安裝zlib庫??梢酝ㄟ^在終端中運行sudo apt-get install zlib1g-dev
來安裝zlib庫。