zlib, c and gzread

so I'm using the zlib package on Ubuntu. I'm trying to figure out how to use gzopen and gzread correctly, this is what I have so far

#include <stdio.h> #include <string.h> #include <assert.h> #include <zlib.h> #define NUM_BUFFERS 8 #define BUFFER_LENGTH 1024 char buf[BUFFER_LENGTH]; int main(int argc, const char* argv[]) { int status; gzFile file; file = gzopen("beowulf.txt", "w"); int counter = 0; /*when the counter reachers BUFFERS_FULL, stop*/ if(file == NULL) { printf("COULD NOT OPEN FILE\n"); return 1; } while(counter < NUM_BUFFERS) { status = gzread(file, buf, BUFFER_LENGTH - 2); printf("STATUS: %d\n", status); buf[BUFFER_LENGTH - 1] = "\0"; printf("%s\n", buf); counter++; } gzclose(file); printf("STATUS: %d\n", status); return 0; } 

The gzread("STATUS: %d\n",status); returns -2, and I have no clue why. Any help would be appreciated.

0

3 Answers

Mode "w" indicates that you are preparing to create a new archive:

file = gzopen("beowulf.txt", "w"); 

You've just truncated the file to zero length.

Also, you should use the binary mode flag: "wb" or "rb".

Also, it's a bit weird that your supposed .gz-archive has an extension .txt.

Read the docs, docs rule. :)

4

Log the error type using function gzerror(). Since it is -2, it won't be an end-of-file error. Possibly any of the following errors.

Z_DATA_ERROR 

A CRC error occurred when reading data; the file is corrupt.

Z_STREAM_ERROR 

The stream is invalid, or is in an invalid state.

Z_NEED_DICT 

A dictionary is needed (see inflateSetDictionary()).

Z_MEM_ERROR 

Insufficient memory available to decompress.

2

From :

  1. If the return is positive it is the number of bytes read, you can use that to put the NULL terminator in the right place.
  2. You can use gzerror if the return code is <0 to work out what the error is.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like