云服务器免费试用

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

服务器知识 0 583

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

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

#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函数用于压缩一个文件。首先打开源文件和目标文件,然后使用zlib库中的deflateInit函数初始化压缩流。接着循环读取源文件数据,并使用deflate函数将数据进行压缩,最后将压缩后的数据写入目标文件。压缩完成后,关闭文件和释放资源。

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

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942@qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c语言压缩文件代码如何写
本文地址: https://solustack.com/156421.html

相关推荐:

网友留言:

我要评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。