程式語言 - GNU - C/C++ - ZIP Compress



main.c

#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <zlib.h>

#define MAX_BUF (32 * 1024 * 1024)

char zip[MAX_BUF] = {0};
char file[MAX_BUF] = {0};
char unzip[MAX_BUF] = {0};

int zip_compress(uint8_t *src, int slen, uint8_t *dst, int dlen)
{
    int err = -1;
    int ret = -1;
    z_stream stream = {0};

    stream.total_in = stream.avail_in = slen;
    stream.total_out = stream.avail_out = dlen;
    stream.next_in = src;
    stream.next_out = dst;
    err = deflateInit(&stream, Z_DEFAULT_COMPRESSION);
    if (err == Z_OK) {
        err = deflate(&stream, Z_FINISH);
        if (err == Z_STREAM_END) {
            ret = stream.total_out;
        }
    }
    deflateEnd(&stream);
    return ret;
}

int zip_decompress(uint8_t *src, int slen, uint8_t *dst, int dlen)
{
    int err = -1;
    int ret = -1;
    z_stream stream = {0};

    stream.total_in = stream.avail_in = slen;
    stream.total_out = stream.avail_out = dlen;
    stream.next_in = src;
    stream.next_out = dst;
    err = inflateInit(&stream);
    if (err == Z_OK) {
        err = inflate(&stream, Z_FINISH);
        if (err == Z_STREAM_END) {
            ret = stream.total_out;
        }
    }
    inflateEnd(&stream);
    return ret;
}

int main(int argc, char **argv)
{
    int r = 0;
    int fd = -1;

    fd = open("test.bin", O_RDONLY);
    r = read(fd, file, sizeof(file));
    close(fd);
    printf("file length: %d\n", r);

    r = zip_compress(file, r, zip, sizeof(zip));
    fd = open("test.zip", O_CREAT | O_WRONLY);
    write(fd, zip, r);
    close(fd);
    printf("zip length: %d\n", r);

    r = zip_decompress(zip, r, unzip, sizeof(unzip));
    fd = open("test.unzip", O_CREAT | O_WRONLY);
    write(fd, unzip, r);
    close(fd);
    printf("unzip length: %d\n", r);
    return 0;
}

編譯、執行

$ gcc main.c -o main -lz
$ echo "123" > test.bin
$ ./main
    file length: 4
    zip length: 12
    unzip length: 4

$ cat test.unzip
    123