c语言

c语言txt文件压缩的方法是什么

小亿
118
2024-05-20 09:29:42
栏目: 编程语言

在C语言中,可以使用一些开源的库来实现txt文件的压缩,比如zlib库。以下是一个简单的示例代码,用来实现txt文件的压缩:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>

#define CHUNK_SIZE 16384

int compress_file(const char *source_file, const char *dest_file) {
    FILE *source = fopen(source_file, "rb");
    if (!source) {
        fprintf(stderr, "Error opening source file\n");
        return -1;
    }

    FILE *dest = fopen(dest_file, "wb");
    if (!dest) {
        fprintf(stderr, "Error opening destination file\n");
        fclose(source);
        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_DEFAULT_COMPRESSION) != Z_OK) {
        fprintf(stderr, "Error initializing zlib\n");
        fclose(source);
        fclose(dest);
        return -1;
    }

    unsigned char in[CHUNK_SIZE];
    unsigned char out[CHUNK_SIZE];

    int ret;
    do {
        stream.avail_in = fread(in, 1, CHUNK_SIZE, source);
        if (ferror(source)) {
            fprintf(stderr, "Error reading from source file\n");
            deflateEnd(&stream);
            fclose(source);
            fclose(dest);
            return -1;
        }
        stream.next_in = in;

        do {
            stream.avail_out = CHUNK_SIZE;
            stream.next_out = out;
            ret = deflate(&stream, stream.avail_in ? Z_NO_FLUSH : Z_FINISH);
            if (ret == Z_STREAM_ERROR) {
                fprintf(stderr, "Error compressing data\n");
                deflateEnd(&stream);
                fclose(source);
                fclose(dest);
                return -1;
            }

            fwrite(out, 1, CHUNK_SIZE - stream.avail_out, dest);
            if (ferror(dest)) {
                fprintf(stderr, "Error writing to destination file\n");
                deflateEnd(&stream);
                fclose(source);
                fclose(dest);
                return -1;
            }
        } while (stream.avail_out == 0);
    } while (ret != Z_STREAM_END);

    deflateEnd(&stream);
    fclose(source);
    fclose(dest);

    return 0;
}

int main() {
    const char *source_file = "source.txt";
    const char *dest_file = "compressed.txt";

    if (compress_file(source_file, dest_file) != 0) {
        fprintf(stderr, "Error compressing file\n");
        return -1;
    }

    printf("File compressed successfully\n");

    return 0;
}

在上面的代码中,我们使用了zlib库中的deflate函数来实现文件的压缩。首先打开源文件和目标文件,然后使用deflateInit函数初始化压缩流。接下来,我们使用一个循环来读取源文件的数据并进行压缩,最后写入目标文件。最后调用deflateEnd函数释放资源并关闭文件。

请注意,以上代码仅供参考,实际使用时需要根据实际情况进行适当的修改和调整。

0
看了该问题的人还看了