c语言压缩文件代码如何写

avatar
作者
猴君
阅读量:0

在C语言中,可以使用zlib库来进行文件的压缩和解压缩操作。以下是一个简单的示例代码,演示如何使用zlib库来压缩一个文件:

#include  #include  #include  #include   #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 filen");         return -1;     }      FILE *dest_file = fopen(dest, "wb");     if (!dest_file) {         fprintf(stderr, "Unable to open destination filen");         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 streamn");         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 successfullyn");     } else {         printf("Failed to compress filen");     }      return 0; } 

在上面的代码中,compress_file函数用于压缩一个文件。首先打开源文件和目标文件,然后使用zlib库中的deflateInit函数初始化压缩流。接着循环读取源文件数据,并使用deflate函数将数据进行压缩,最后将压缩后的数据写入目标文件。压缩完成后,关闭文件和释放资源。

注意:在编译这段代码之前,需要安装zlib库。可以通过在终端中运行sudo apt-get install zlib1g-dev来安装zlib库。

    广告一刻

    为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!