Linux readdir如何实现文件压缩与解压

Linux readdir如何实现文件压缩与解压 alt="linux readdir实现文件压缩与解压" />

Linux环境下,readdir函数主要用于列出目录中的文件和子目录。尽管readdir本身并不提供文件压缩与解压的功能,但可以借助其他库和工具来完成这一任务。

下面是一个使用C语言及zlib库来实现文件压缩与解压的例子。在执行前,请确认系统已安装zlib库。

压缩文件

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <zlib.h><p>int compress_file(const char <em>input_filename, const char </em>output_filename) {FILE *input_file = fopen(input_filename, "rb");if (!input_file) {perror("无法打开输入文件");return -1;}</p><pre class="brush:php;toolbar:false">FILE *output_file = fopen(output_filename, "wb");if (!output_file) {    perror("无法打开输出文件");    fclose(input_file);    return -1;}int ret, flush;unsigned have;z_stream strm;unsigned char in[4096];unsigned char out[4096];strm.zalloc = Z_NULL;strm.zfree = Z_NULL;strm.opaque = Z_NULL;ret = deflateInit(&strm, Z_DEFAULT_COMPRESSION);if (ret != Z_OK) {    fprintf(stderr, "deflateInit错误 %dn", ret);    fclose(input_file);    fclose(output_file);    return -1;}do {    strm.avail_in = fread(in, 1, sizeof(in), input_file);    if (ferror(input_file)) {        (void)deflateEnd(&strm);        fclose(input_file);        fclose(output_file);        return -1;    }    flush = feof(input_file) ? Z_FINISH : Z_NO_FLUSH;    strm.next_in = in;    do {        strm.avail_out = sizeof(out);        strm.next_out = out;        ret = deflate(&strm, flush);        have = sizeof(out) - strm.avail_out;        if (fwrite(out, 1, have, output_file) != have || ferror(output_file)) {            (void)deflateEnd(&strm);            fclose(input_file);            fclose(output_file);            return -1;        }    } while (strm.avail_out == 0);} while (flush != Z_FINISH);(void)deflateEnd(&strm);fclose(input_file);fclose(output_file);return 0;

登录后复制

文章来自互联网,不代表电脑知识网立场。发布者:,转载请注明出处:https://www.pcxun.com/n/659213.html

(0)
上一篇 2025-05-25 13:35
下一篇 2025-05-25 13:35

相关推荐