HOME > Zlib Utility Function Manual

 

Zlib Utility Function Manual

 

 

Function list

typedef unsigned char Bytef;
typedef unsigned long uLong;
typedef void *voidp;
typedef voidp gzFile;
  

Function description – Visual C++ 6.0용 예제 소스 파일 링크

int compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);

Compresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least 0.1% larger than sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.

This function can be used to compress a whole file at once if the input file is mmap'ed.

(Error Return)
Z_OK if success
Z_MEM_ERROR if there was not enough memory
Z_BUF_ERROR if there was not enough room in the output buffer.

(예제)
unsigned char* inbuf=new unsigned char[1000];
strcpy((char*)inbuf,"Is good?");
unsigned int INBUFSIZE=strlen((char*)inbuf)+1;


//Integer의 반올림 문제 때문에 1을 더했다.
unsigned int OUTBUFSIZE=(unsigned long)1.001*(INBUFSIZE+12) + 1;
unsigned char* outbuf=new unsigned char[OUTBUFSIZE];

 

//Compression Level은 링크를 참조하라.

int err=compress(outbuf, &OUTBUFSIZE, inbuf, INBUFSIZE);

if( err==Z_OK ){

fprintf(stderr,"compress함수로 압축했습니다.\n\n");

}

else{   // 압축에 실패한 경우

               fprintf(stderr,"압축에 실패했습니다.\n");

               // 반환된 에러 메시지를 출력한다.

fprintf(stderr,"Error code = %d\n",err);

exit(1);
}

 

int compress2 (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level);

Compresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least 0.1% larger than sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.

 

(Error Return)

Z_OK if success

Z_MEM_ERROR if there was not enough memory

Z_BUF_ERROR if there was not enough room in the output buffer

Z_STREAM_ERROR if the level parameter is invalid.

(예제)
//Integer의 반올림 문제 때문에 1을 더했다.
unsigned char*
inbuf=new unsigned char[1000];
strcpy((char*)inbuf,"Is good?");
unsigned int INBUFSIZE=strlen((char*)inbuf)+1;

unsigned int OUTBUFSIZE=(unsigned long)1.001*(INBUFSIZE+12) + 1;
unsigned char* outbuf=new unsigned char[OUTBUFSIZE];

        //Compression Level은 링크를 참조하라.

        int err=compress(outbuf, &OUTBUFSIZE, inbuf, INBUFSIZE, Z_DEFAULT_COMPRESSION);

       

        //Error code에 대해 알고 싶다면 링크를 참조하라.

if( err==Z_OK ){

               fprintf(stderr,"compress함수로 압축했습니다.\n\n");

        }

        else{

               fprintf(stderr,"압축에 실패했습니다.\n");

fprintf(stderr,"Error code = %d\n",err);

exit(1);
}

 

 

int uncompress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);

Decompresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the compressed buffer.

 

This function can be used to decompress a whole file at once if the input file is mmap'ed.

 

(Error Return)

Z_OK if success

Z_MEM_ERROR if there was not enough memory

Z_BUF_ERROR if there was not enough room in the output buffer

Z_DATA_ERROR if the input data was corrupted.


(예제) – compress 함수의 예제와 연결된다.
int err=uncompress(inbuf,&INBUFSIZE,outbuf,OUTBUFSIZE);

        if( err==Z_OK ){

               fprintf(stderr,"uncompress함수로 압축 해제된 내용은 다음과 같다.\n");

               fprintf(stderr,"%s\n\n",inbuf);

        } else{

               fprintf(stderr,"압축 해제에 실패했습니다.\n");

               fprintf(stderr,"Error code = %d\n",err);

               exit(1);

}

(성공했을 경우의 출력 결과)
uncompress함수로 압축 해제된 내용은 다음과 같다.
Is good?


 

gzFile gzopen (const char *path, const char *mode);

Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman only compression as in "wb1h". (Click this link for more information about the strategy parameter.)

 

gzopen can be used to read a file which is not in gzip format ; in this case gzread will directly read from the file without decompression.

 

(Error Return)

NULL if the file could not be opened or if there was insufficient memory to allocate the (de)compression state;

 

errno can be checked to distinguish the two cases (if errno is zero, the zlib error is Z_MEM_ERROR).

(예제)
int err;

char* filename = new char[100];
strcpy(filename,"gzip.gz");

//The mode parameter is as in fopen ("rb" or "wb")
gzFile
file = gzopen(filename, "rb");
if (file == NULL){     //gzip 파일 열기에 실패한 경우

fprintf(stderr, "gzopen(%s,\"wb\") error: %s\n",filename,gzerror(file,&err));

               exit(1);

}

 

 

gzFile gzdopen (int fd, const char *mode);

gzdopen () associates a gzFile with the file descriptor fd. File descriptors are obtained from calls like open, dup, creat, pipe or fileno (in the file has been previously opened with fopen). The mode parameter is as in gzopen.

 

The next call of gzclose on the returned gzFile will also close the file descriptor fd, just like fclose(fdopen(fd), mode) closes the file descriptor fd. If you want to keep fd open, use gzdopne(dup(fd), mode).

 

(Error Return)

NULL if there was insufficient memory to allocate the (de)compression state.



int gzsetparams (gzFile file, int level, int strategy);

Dynamically update the compression level or strategy. See the description of deflateInit2 for the meaning of these parameters.

 

(Error Return)

Z_OK if success

Z_STREAM_ERROR if the file was not opened for writing.

 

 

int gzread (gzFile file, voidp buf, unsigned len);

Reads the given number of uncompressed bytes from the compressed file. If the input file was not in gzip format, gzread copies the given number of bytes into the buffer.

 

(Error Return)

The number of uncompressed bytes actually read

0 for end of file, -1 for error

(예제)

unsigned int OUTBUFSIZE;

unsigned char* outbuf;
//바이너리 파일을 읽기 모드로 연다.

        FILE* fin=fopen(filename,"rb");

        if( fin==NULL ){

               fprintf(stderr, "fopen(%s,\"rb\") error! \n\n",filename);

               exit(1);

        }

        //우선 원본 파일의 사이즈를 알아낸다.

        //gzseek()함수에서 SEEK_END가 지원되지 않기 때문에 여기서는 fopen을 사용했다.

        //gzip의 파일 포맷을 알고 있다면, 여기를 클릭하라.

        fseek(fin,-4,SEEK_END);

        fread(&OUTBUFSIZE,sizeof(int),1,fin);

        fprintf(stdout,"Original file size = %d\n",OUTBUFSIZE);

        outbuf=new char[OUTBUFSIZE];

        
gzFile file = gzopen(filename, "rb"); //읽기 모드로 gzip파일을 연다.
        if (file == NULL){     //gzip 파일 열기에 실패한 경우

               fprintf(stderr, "gzopen(%s,\"wb\") error: \n\n",filename,gzerror(file,&err));

               exit(1);

}

        /* gzread()함수 - gzip파일을 압축 해제한다. */          

int _OUTBUFSIZE = gzread(file, outbuf, (unsigned)OUTBUFSIZE);

// gzip파일에 기록된 원본 파일 사이즈 기록이 정확한지 확인해 본다.
if (OUTBUFSIZE != _OUTBUFSIZE) {

        fprintf(stderr,"gzread(file,outbuf,(unsigned)OUTBUFSIZE) err: %s\n", gzerror(file, &err));

               exit(1);

}

 

 

int gzwrite (gzFile file, const voidp buf, unsigned len);

Writes the given number of uncompressed bytes into the compressed file.

 

(Error Return)

The number of uncompressed bytes actually written

0 in case of error.

 

 

int VA gzprintf (gzFile file, const char *format, ...);

Converts, formats, and writes the args to the compressed file under control of the format string, as in fprintf.

 

(Error Return)

The number of uncompressed bytes actually written

(0 in case of error).

 

(예제) gzopen 함수 예제에서 이어지는 내용이다.

if (gzprintf(file, " %s", "Keys") == 0 ){     //실패한 경우

               fprintf(stderr, "gzprintf(file, \" %s\") error: \n\n","Keys",gzerror(file,&err));

               exit(1);

}

 

 

int gzputs (gzFile file, const char *s);

Writes the given null-terminated string to the compressed file, excluding the terminating null character.

 

(Error Return)

The number of characters written

-1 in case of error.

(예제) gzopen 함수 예제에서 이어지는 내용이다.

if (gzputs(file, "licia") == -1 ){ //실패한 경우

        fprintf(stderr, "gzputs(file,\"licia\") err: %s\n\n", gzerror(file, &err));

               exit(1);

}

 

char * gzgets (gzFile file, char *buf, int len);

Reads bytes from the compressed file until len-1 characters are read, or a newline character is read and transferred to buf, or an end-of-file condition is encountered. The string is then terminated with a null character.

 

(Error Return)

buf

Z_NULL in case of error.

 

int gzputc (gzFile file, int c);

Writes c, converted to an unsigned char, into the compressed file.

 

(Error Return)

the value that was written

-1 in case of error.

 

 

int gzgetc (gzFile file);

Reads one byte from the compressed file.

 

(Error Return)

this byte

-1 in case of end of file or error.

 

(예제)gzeof 의 예제를 보라.

 

 

int gzflush (gzFile file, int flush);

Flushes all pending output into the compressed file. The parameter flush is as in the deflate() function. The return value is the zlib error number (see function gzerror below).

 

gzflush should be called only when strictly necessary because it can degrade compression.

(Error Return)

Z_OK if the flush parameter is Z_FINISH and all output could be flushed.

 

 

z_off_t gzseek (gzFile file, z_off_t offset, int whence);

Sets the starting position for the next gzread or gzwrite on the given compressed file. The offset represents a number of bytes in the uncompressed data stream. The whence parameter is defined as in lseek(2); the value SEEK_END is not supported.

 

If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported ; gzseek then compresses a sequence of zeroes up to the new starting position.

 

(Error Return)

the resulting offset location as measured in bytes from the beginning of the uncompressed stream

 

-1 in case of error, in particular if the file is opened for writing and the new starting position would be before the current position.

 

int gzrewind (gzFile file);

Rewinds the given file. This function is supported only for reading.

gzrewind (file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)

 

z_off_t gztell (gzFile file);

Returns the starting position for the next gzread or gzwrite on the given compressed file.

This position represents a number of bytes in the uncompressed data stream.


gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)

 

int gzeof (gzFile file);

Returns 1 when EOF has previously been detected reading the given input stream, otherwise zero.

 

(예제)

        char _str[2];

_str[1]='\0';

gzrewind(file);

 

while( gzeof(file)==0 )

{

               /* int gzgetc (gzFile file) */

               //Reads one byte from the compressed file.

               //gzgetc returns this byte or -1 in case of end of file or error.

               _str[0]=gzgetc(file);

               strcat(outbuf,_str);

}

 

 

int gzclose (gzFile file);

Flushes all pending output if necessary, closes the compressed file and deallocates all the (de)compression state. The return value is the zlib error number (see function gzerror below).

 

 

const char * gzerror (gzFile file, int *errnum);

Returns the error message for the last error which occurred on the given compressed file. errnum is set to zlib error number. If an error occurred in the file system and not in the compression library, errnum is set to Z_ERRNO and the application may consult errno to get the exact error code.

 

           (예제) gzopen의 예제를 보라.