2010-01-20 2 views
4

저는 zlib을 사용하여 gzip 압축을 수행하고 있습니다. zlib은 데이터를 압축 한 후 열려있는 TCP 소켓에 직접 데이터를 씁니다.gzip으로 압축 된 데이터의 zlib에서 압축 된 크기를 결정하는 방법은 무엇입니까?

/* socket_fd is a file descriptor for an open TCP socket */ 
gzFile gzf = gzdopen(socket_fd, "wb"); 
int uncompressed_bytes_consumed = gzwrite(gzf, buffer, 1024); 

(물론 모든 오류 처리가 제거)

질문입니다 : 어떻게 소켓에 기록 된 바이트 수를 확인할 수 있습니까? zlib의 모든 gz * 함수는 압축되지 않은 도메인의 바이트 수/오프셋을 처리하며 tell (seek)은 소켓에서 작동하지 않습니다.

zlib.h 헤더에 "이 라이브러리는 선택적으로 메모리에 gzip 스트림을 읽고 쓸 수 있습니다."라는 메시지가 표시됩니다. 버퍼에 쓰는 것은 작동 할 것입니다 (그 다음에는 소켓에 버퍼를 쓸 수 있습니다). 그러나 인터페이스를 사용하여 버퍼를 작성하는 방법을 알 수 없습니다.

답변

0

zlib은 사실 gzip 형식의 데이터를 메모리의 버퍼에 쓸 수 있습니다.

zlib faq 항목은 zlib.h의 주석을 사용하지 않습니다. 헤더 파일에서 deflateInit2()에 대한 주석은 라이브러리가 기본 "zlib"대신 gzip 형식의 수축 스트림을 포맷하도록하기 위해 네 번째 매개 변수 (windowBits)에 16을 (임의로) 추가해야한다고 언급합니다 "형식).

이 코드는 ZLIB 상태 버퍼에 GZIP 인코딩을 적절히 설정 얻는다 :

#include <zlib.h> 
z_stream stream; 
stream.zalloc = Z_NULL; 
stream.zfree = Z_NULL; 
stream.opaque = Z_NULL; 
int level = Z_DEFAULT_COMPRESSION; 
int method = Z_DEFLATED; /* mandatory */ 
int windowBits = 15 + 16; /* 15 is default as if deflateInit */ 
          /* were used, add 16 to enable gzip format */ 
int memLevel = 8;   /* default */ 
int strategy = Z_DEFAULT_STRATEGY; 
if(deflateInit2(&stream, level, method, windowBits, memLevel, strategy) != Z_OK) 
{ 
    fprintf(stderr, "deflateInit failed\n"); 
    exit(EXIT_FAILURE); 
} 

/* now use the deflate function as usual to gzip compress */ 
/* from one buffer to another. */ 

나가이 절차는 gzopen/gzwrite/gzclose 인터페이스와 동일한 이진 출력을 얻을 수 있음을 확인 하였다.

0

deflate* 일련의 통화로이 작업을 수행 할 수 있습니다. 나는 당신에게 모든 것을 보여 않을거야,하지만 (나는 내 ​​디렉토리에 "TEST.C"라는 한)이 예제 프로그램은 당신이 시작하는 데 도움이 될 것입니다

#include <zlib.h> 
#include <stdlib.h> 
#include <stdio.h> 

char InputBufferA[4096]; 
char OutputBufferA[4096]; 

int main(int argc, char *argv[]) 
{ 
    z_stream Stream; 
    int InputSize; 
    FILE *FileP; 

    Stream.zalloc = malloc; 
    Stream.zfree = free; 
    /* initialize compression */ 
    deflateInit(&Stream, 3); 
    FileP = fopen("test.c", "rb"); 
    InputSize = fread((void *) InputBufferA, 1, sizeof(InputBufferA), FileP); 
    fclose(FileP); 
    Stream.next_in = InputBufferA; 
    Stream.avail_in = InputSize; 
    Stream.next_out = OutputBufferA; 
    Stream.avail_out = sizeof(OutputBufferA); 
    deflate(&Stream, Z_SYNC_FLUSH); 
    /* OutputBufferA is now filled in with the compressed data. */ 
    printf("%d bytes input compressed to %d bytes\n", Stream.total_in, Stream.total_out); 
    exit(0); 
} 

zlib.h에서 deflate 설명서를 참조하십시오.

+1

내가 뭔가를 놓치고 있는지 확실하지 않지만 gzip 형식의 데이터가 생성되지 않는 것 같습니다. – Andrew