It could be a silly question. When I tried to uncompress a compressed data in memory, got error. Here is the code.
#include <zlib.h>
#include <stdio.h>
#include <stdlib.h>
int readFile(char *fname, char buf[]) {
FILE *fp = fopen(fname, "rb");
if (fp == NULL) { printf("Failed to open %s\n", fname); exit(0);}
int n = fread(buf, 1, 0x100000, fp);
fclose(fp);
return n;
}
char buf[2][0x10000];
int main(int argc, char *argv[]) {
long n = readFile(argv[1], &buf[0][0]);
unsigned int *pInt = (unsigned int*) (&buf[0][0]);
printf("n=%d %08x\n", n, *pInt);
long m = 0x10000;
int rc = uncompress(&buf[1][0], &m, &buf[0][0], n);
printf("rc = %d %s\n", rc, &buf[1][0]);
return 0;
}
Got error:
./a.out te.html.gz
n=169 08088b1f
rc = -3
te.html.gz is obtained from by running `gzip te.html'.
Thanks!
zlib format is not gzip format. The zlib uncompress
function doesn't understand the gzip format.
You can generate some zlib format test data by writing a similar program that calls the compress
function in zlib. Or you could use the openssl zlib
command, if you have openssl installed.
A complete, working example on uncompressing gzipped data (thanks to link)
#include <zlib.h>
#include <stdio.h>
#include <stdlib.h>
int readFile(char *fname, char buf[]) {
FILE *fp = fopen(fname, "rb");
if (fp == NULL) { printf("Failed to open %s\n", fname); exit(0);}
int n = fread(buf, 1, 0x100000, fp);
fclose(fp);
return n;
}
int inf(const char *src, int srcLen, const char *dst, int dstLen){
z_stream strm;
strm.zalloc=NULL;
strm.zfree=NULL;
strm.opaque=NULL;
strm.avail_in = srcLen;
strm.avail_out = dstLen;
strm.next_in = (Bytef *)src;
strm.next_out = (Bytef *)dst;
int err=-1, ret=-1;
err = inflateInit2(&strm, MAX_WBITS+16);
if (err == Z_OK){
err = inflate(&strm, Z_FINISH);
if (err == Z_STREAM_END){
ret = strm.total_out;
}
else{
inflateEnd(&strm);
return err;
}
}
else{
inflateEnd(&strm);
return err;
}
inflateEnd(&strm);
printf("%s\n", dst);
return err;
}
char buf[2][0x10000];
int main(int argc, char *argv[]) {
long n = readFile(argv[1], &buf[0][0]);
unsigned int *pInt = (unsigned int*) (&buf[0][0]);
printf("n=%d %08x\n", n, *pInt);
long m = 0x10000;
int rc = inf(&buf[0][0], n, &buf[1][0], m);
printf("rc = %d %s\n", rc, &buf[1][0]);
return 0;
}