2014-01-17 2 views
1

zlib 함수 compress() 및 uncompress()를 사용하여 문자열을 압축 한 다음 압축을 풀어야하는 프로그램을 작성했습니다. 어떤 이유로, 내가 시작할 때 압축되지 않은 문자열의 일부 기호가 누락되었습니다. "일부"와 몇 가지 시스템 기호가 있습니다. 누구든지 여기서 실수를 찾는데 도와 줄 수 있습니까?zlib을 사용하여 문자 배열을 압축/압축 해제

#include "string.h" 
#include "stdio.h" 
#include "stdlib.h" 
#include "zlib.h" 
int main() 
{ 
const char *istream = "some foo"; 
ulong destLen = strlen(istream); 
char* ostream = malloc(2 * strlen(istream)); 
int res = compress(ostream, &destLen, istream, destLen + 1); 


const char *i2stream = ostream; 
char* o2stream = malloc(4 * strlen(istream)); 
ulong destLen2 = strlen(i2stream); 
int des = uncompress(o2stream, &destLen2, i2stream, destLen2); 
printf("%s", o2stream); 
return 0; 
} 
+0

이 코드 나 strlen의 많은()가있다. –

+0

그것은 지금까지 최적화되지 않았으며, 이것은 단지 프로토 타입 일 뿐이므로 이것을 2 개의 함수로 나눌 계획입니다. 의도 한대로 작동하지 않습니다. 이유는 없습니다. – FalconD

+0

압축 된 데이터가 어떻게 들어 맞는지 어떻게 알 수 있습니까? 짧은 입력을위한 '2 * strlen (istream)'크기의'ostream'? 'Z_MEM_ERROR' 또는'Z_MEM_ERROR'에 대한 압축 결과를 확인 했습니까? – luk32

답변

4

오류 코드를 확인하십시오 !!

luk32:gcc -lz ./zlib.c 
luk32:~/projects/tests$ ./a.out 
Buffer was too small! 

아주 작은 입력에는 압축이 효과적이지 않을 때가 있습니다. 따라서 필요한 버퍼 크기가 2*strlen(istream) 인 것에 대한 예측은 과소 평가되었습니다.

는 무엇이 잘못되었는지 확인 zlib.c을 "개선"

#include "string.h" 
#include "stdio.h" 
#include "stdlib.h" 
#include "zlib.h" 
int main() 
{ 
    const char *istream = "some foo"; 
    ulong destLen = strlen(istream); 
    char* ostream = malloc(2 * strlen(istream)); 
    int res = compress(ostream, &destLen, istream, destLen + 1); 
    if(res == Z_BUF_ERROR){ 
    printf("Buffer was too small!\n"); 
    return 1; 
    } 
    if(res == Z_MEM_ERROR){ 
    printf("Not enough memory for compression!\n"); 
    return 2; 
    } 
} 

문서에서 "Utility Functions"주의 깊게 읽은 후. 전체 올바른 코드 :

#include "string.h" 
#include "stdio.h" 
#include "stdlib.h" 
#include "zlib.h" 
int main() 
{ 
    const char *istream = "some foo"; 
    ulong srcLen = strlen(istream)+1;  // +1 for the trailing `\0` 
    ulong destLen = compressBound(srcLen); // this is how you should estimate size 
             // needed for the buffer 
    char* ostream = malloc(destLen); 
    int res = compress(ostream, &destLen, istream, srcLen); 
    // destLen is now the size of actuall buffer needed for compression 
    // you don't want to uncompress whole buffer later, just the used part 
    if(res == Z_BUF_ERROR){ 
    printf("Buffer was too small!\n"); 
    return 1; 
    } 
    if(res == Z_MEM_ERROR){ 
    printf("Not enough memory for compression!\n"); 
    return 2; 
    } 

    const char *i2stream = ostream; 
    char* o2stream = malloc(srcLen); 
    ulong destLen2 = destLen; //destLen is the actual size of the compressed buffer 
    int des = uncompress(o2stream, &srcLen, i2stream, destLen2); 
    printf("%s\n", o2stream); 
    return 0; 
} 

테스트 :

luk32:gcc -lz ./zlib.c 
luk32:~/projects/tests$ ./a.out 
some foo 
관련 문제