在内存中压缩及解压缩
//引入头文件#import <zlib.h> //引入libz动态库 NSString *str = @"zlib compress and uncompress test\[email protected]\n2012-11-05\n"; NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; Bytef *text = (Bytef*)[data bytes]; uLong tlen = [data length]; char* buf = NULL; uLong blen; /* 计算缓冲区大小,并为其分配内存 */ blen = compressBound(tlen); /* 压缩后的长度是不会超过blen的 */ if((buf = (char*)malloc(sizeof(char) * blen)) == NULL) { printf("no enough memory!\n"); return -1; } /* 压缩 */ if(compress((Bytef*)buf, &blen, (Bytef*)text, tlen) != Z_OK) { printf("compress failed!\n"); return -1; } /* 解压缩 */ if(uncompress((Bytef*)text, &tlen, (Bytef*)buf, blen) != Z_OK) { printf("uncompress failed!\n"); return -1; } /* 打印结果,并释放内存 */ printf("%s", text); if(buf != NULL) { free(buf); buf = NULL; }
时间: 2024-10-14 00:53:34