zlib 压缩使用

1. 下载zlib. 目录好像 是1.2.3

2.  编译 zlib.

     打开 \zlib-1.2.3\projects\visualc6,打开 zlib.dsw, 如果没有VC6,可以用VS2003,VS2005,VS2008等编译器强制转换。

3. 示例

// zlib_test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "zlib.h"

#pragma comment (lib, "zlib1.lib")



void
CheckVersion (void);

bool
Compress (Byte* pbOut, uLong* pulOutLen, const Byte* pbIn, uLong ulInLen);

bool
Uncompress (Byte* pbOut, uLong* pulOutLen, const Byte* pbIn, uLong ulInLen);


int _tmain(int argc, _TCHAR* argv[])
{
    CheckVersion();
    const char* pbToCompress = "Hello World!";
    char* pbCompressed = (char*)calloc (128, 1);
    uLong ulCompressed = 128;
    if (!Compress((Byte*)pbCompressed, &ulCompressed, (const Byte*)pbToCompress, strlen (pbToCompress) + 1)) {
        printf("compress failed.\n");
        getchar ();
        exit (0);
    }
    printf ("Compress successfully.\n");

    char* pbUncompress = (char*)calloc (128, 1);
    uLong ulUncompress = 128;

    if (!Uncompress((Byte*)pbUncompress, &ulUncompress, (const Byte*)pbCompressed, ulCompressed)) {
        printf ("uncompress failed.\n");
        getchar ();
        exit (0);
    }

    printf("compressed: %s\n", pbUncompress);


//========================================================================
//文件操作
    gzFile file = gzopen ("d:\\a.gz", "wb");
    if (file == NULL) {
        printf("cannot open c:\\a.gz\n");
        getchar ();
        exit(0);
    }
    
    if (strlen (pbToCompress) != gzprintf (file, "%s", pbToCompress)) {
        printf("write gz file failed\n");
        getchar ();
        exit(0);
    }
    printf("write gz file successfully\n");
    gzclose (file);

    file = gzopen ("d:\\a.gz", "rb");
    if (file == NULL) {
        printf("cannot open read file d:\\a.gz\n");
        getchar (0);
        exit(0);
    }
    char szToRead [128] = {0};
    uLong ulReadLen = 128;

    if (strlen (pbToCompress) != gzread (file, szToRead, ulReadLen)) {
        printf("read failed.\n");
    }
    printf("read successfully\n");
    printf("gz file:%s", szToRead);

    gzclose (file);

    getchar ();
    return 0;
}



void
CheckVersion (void)
{
    const char* myVersion = ZLIB_VERSION;
    if (zlibVersion()[0] != myVersion[0]) {
        fprintf(stderr, "incompatible zlib version\n");
        getchar ();
        exit(1);

    } else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) {
        fprintf(stderr, "warning: different zlib version\n");
    }
}

bool
Compress (Byte* pbOut, uLong* pulOutLen, const Byte* pbIn, uLong ulInLen)
{
    int error = compress(pbOut, pulOutLen, (const Bytef*)pbIn, ulInLen);
    return (Z_OK == error);
}

bool
Uncompress (Byte* pbOut, uLong* pulOutLen, const Byte* pbIn, uLong ulInLen)
{
    int error = uncompress (pbOut, pulOutLen, (const Bytef*)pbIn, ulInLen);
    return (Z_OK == error);
}
原文地址:https://www.cnblogs.com/lin1270/p/2456755.html