zlib 라이브러리를 사용해봅시다. 가장 기본적인 사용법은 압축입니다.
압축 연산은 3 함수로 구성됩니다.
- deflateInit – 메모리 할당 및 내부 상태 변수 할당
- deflate – 실제 압축
- deflateEnd – 할당 메모리 소거
동영상 강좌 샘플 코딩
// Sample1_Deflate.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <LibZ/zlib.h>
#include <fstream>
int _tmain(int argc, _TCHAR* argv[])
{
std::ifstream fp;
fp.open("test.bmp",std::ios_base::binary);
if(!fp ) return 0;
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
// 메모리 할당
int ret = deflateInit(&stream,Z_DEFAULT_COMPRESSION);
if( Z_OK != ret){
fp.close();
return 0;
}
// 압축 코딩이... 위치하게 됨.
const int BUF=1024;
Bytef in[BUF];
Bytef out[BUF];
std::ofstream wp;
wp.open("test.enc", std::ios_base::binary);
do{
fp.read((char*)in, BUF);
int readsize = (int)fp.gcount();
//입력 버퍼 설정
stream.avail_in = readsize;
stream.next_in = in;
int flush = Z_NO_FLUSH;
if( fp.eof() ) {flush = Z_FINISH;}
do{// 모든 입력 버퍼 연산 실행
//입력 버퍼 설정
stream.avail_out = BUF;
stream.next_out = out;
ret = deflate(&stream,flush);
//실행된 결과 저장
int dsize = BUF - stream.avail_out;
wp.write(( const char*)out,dsize);
} while( 0==stream.avail_out);
}while(Z_STREAM_END != ret);
wp.close();
deflateEnd(&stream);// 메모리 해제
fp.close();
return 0;
}