#include "stdafx.h" // not actually needed
#define ZLIB_WINAPI // actually actually needed (for linkage)
#include "windows.h" // get BYTE et al.
#include "zlib.h" // declare the external fns -- uses zconf.h, too
#pragma comment(lib, "zlibwapi.lib") // for access to the DLL
int GetMaxCompressedLen( int nLenSrc )
{
int n16kBlocks = (nLenSrc+16383) / 16384; // round up any fraction of a block
return ( nLenSrc + 6 + (n16kBlocks*5) );
}
int CompressData( const BYTE* abSrc, int nLenSrc, BYTE* abDst, int nLenDst )
{
z_stream zInfo ={0};
zInfo.total_in= zInfo.avail_in= nLenSrc;
zInfo.total_out= zInfo.avail_out= nLenDst;
zInfo.next_in= (BYTE*)abSrc;
zInfo.next_out= abDst;
int nErr, nRet= -1;
nErr= deflateInit( &zInfo, Z_DEFAULT_COMPRESSION ); // zlib function
if ( nErr == Z_OK ) {
nErr= deflate( &zInfo, Z_FINISH ); // zlib function
if ( nErr == Z_STREAM_END ) {
nRet= zInfo.total_out;
}
}
deflateEnd( &zInfo ); // zlib function
return( nRet );
}
int UncompressData( const BYTE* abSrc, int nLenSrc, BYTE* abDst, int nLenDst )
{
z_stream zInfo ={0};
zInfo.total_in= zInfo.avail_in= nLenSrc;
zInfo.total_out= zInfo.avail_out= nLenDst;
zInfo.next_in= (BYTE*)abSrc;
zInfo.next_out= abDst;
int nErr, nRet= -1;
nErr= inflateInit( &zInfo ); // zlib function
if ( nErr == Z_OK ) {
nErr= inflate( &zInfo, Z_FINISH ); // zlib function
if ( nErr == Z_STREAM_END ) {
nRet= zInfo.total_out;
}
}
inflateEnd( &zInfo ); // zlib function
return( nRet ); // -1 or len of output
}
This defines three functions that simplify using the library for in-memory operation:
int main()
{
BYTE pbSrc[]="hello hello hello hello there";
//-------------- compress (save the original length)
int nLenOrig= strlen( (char*)pbSrc )+1; // include terminating NULL
int nLenDst= GetMaxCompressedLen( nLenOrig );
BYTE* pbDst= new BYTE [nLenDst]; // alloc dest buffer
int nLenPacked= CompressData( pbSrc, nLenOrig, pbDst, nLenDst );
if ( nLenPacked == -1 ) return(1); // error
//-------------- uncompress (uses the saved original length)
BYTE* pbPacked= pbDst;
BYTE* pbUnpacked= new BYTE[ nLenOrig ];
int nLen= UncompressData( pbPacked, nLenPacked, pbUnpacked, nLenOrig );
// breakpoint here and view pbUnpacked to confirm
delete pbDst; // do some cleanup
delete pbUnpacked;
return 0;
}
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (5)
Commented:
just swap deflateEnd( &zInfo ) and deflateEnd( &zInfo ) to fix it. rtfm, bye.
Author
Commented:-- Dan
Commented:
Commented:
Commented: