Reputation: 105
I am having some trouble inflating a simple HTML file using zlib that has been compressed using gzip.
The file is below along with the steps I am taking to open it as well as the inflation function I am attempting to use. When I run the function I get zlib's error code Z_DATA_ERROR. From what I can tell I have stuck faithfully to zlib's usage example (found here) but nonetheless I am having some trouble.
The inflation routine doesn't turn up an error until after the inflate() method is called and the function returns in the switch statement, but I haven't been able to track down just what the problem is.
Any help here would be much appreciated.
Compressed file:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>TEST</title>
</head>
<body>
<ul>
<li>hello</li>
<li>I</li>
<li>am</li>
<li>a</li>
<li>test</li>
<li>web</li>
<li>page</li>
</ul>
</body>
</html>
Note: These are the file contents before gzip compression.
File opening: sourcefile here is then passed in inf().
FILE *sourcefile;
sourcefile = fopen("/Users/me/pathtofile/test.html.gz", "r");
Inflate routine:
inf(FILE *source, FILE *dest){
int chunk = 16384;
//setup zlib variables
int return_val;
unsigned have;
z_stream z_strm;
unsigned char in[chunk];
unsigned char out[chunk];
//allocate inflate state
z_strm.zalloc = Z_NULL;
z_strm.zfree = Z_NULL;
z_strm.opaque = Z_NULL;
z_strm.avail_in = 0;
z_strm.next_in = Z_NULL;
return_val = inflateInit(&z_strm);
if(return_val != Z_OK){
return return_val;
}
cout << "zlib setup complete" << endl;
//decompress
do{
z_strm.avail_in = fread(in, 1, chunk, source);
//check for error
if (ferror(source)){
(void)inflateEnd(&z_strm);
return Z_ERRNO;
}
if(z_strm.avail_in == 0){
break;
}
z_strm.next_in = in;
cout << "inflate loop") << endl;
//inflate the data
do{
z_strm.avail_out = chunk;
z_strm.next_out = out;
return_val = inflate(&z_strm, Z_NO_FLUSH);
assert(return_val != Z_STREAM_ERROR);
cout << "switch statement start" << endl;
switch(return_val){
case Z_NEED_DICT:
return_val = Z_DATA_ERROR;
cout << "case: Z_NEED_DICT" << endl;
case Z_DATA_ERROR:
cout<< "case: Z_DATA_ERROR" << endl;
case Z_MEM_ERROR:
cout << "case: Z_MEM_ERROR" << endl;
void(inflateEnd(&z_strm));
return return_val;
}
cout << "switch statement end" << endl;
have = chunk - z_strm.avail_out;
if(fwrite(out, 1, have, dest) != have || ferror(dest)){
(void)inflateEnd(&z_strm);
return Z_ERRNO;
}
}while(z_strm.avail_out == 0);
}while(return_val != Z_STREAM_END);
}
Upvotes: 1
Views: 5852
Reputation: 1401
The main reason could be you have wrong initialization
inflateInit2(&z_strm,15+32)
and for inflate
inflate(&z_strm, Z_SYNC_FLUSH );
Could solve your problem .
Upvotes: 0
Reputation: 112239
You need to use inflateInit2()
instead of inflateInit()
to request decoding of the gzip format. zlib by default is looking for the zlib format.
Upvotes: 1