Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening gzipped files for reading in C without creating temporary files

Tags:

c

file-io

gzip

I have some gzipped files that I want to read in C via fopen and fscanf. Is there anyway to do this without having to gunzip the files to temporary files?

Thanks.

like image 461
Switch Avatar asked Nov 30 '09 14:11

Switch


2 Answers

You can use zlib and wrap it to a regular file pointer, this way you can use fscanf,fread,etc. transparently.

FILE *myfopen(const char *path, const char *mode)
{
#ifdef WITH_ZLIB
  gzFile *zfp;

  /* try gzopen */
  zfp = gzopen(path,mode);
  if (zfp == NULL)
    return fopen(path,mode);

  /* open file pointer */
  return funopen(zfp,
                 (int(*)(void*,char*,int))gzread,
                 (int(*)(void*,const char*,int))gzwrite,
                 (fpos_t(*)(void*,fpos_t,int))gzseek,
                 (int(*)(void*))gzclose);
#else
  return fopen(path,mode);
#endif
}
like image 61
Fernando Mut Avatar answered Oct 15 '22 20:10

Fernando Mut


You can use libzlib to open the gzipped files directly.

It also offers a "gzopen" function that behaves similar to fopen but operates on gzipped files. However, fscanf would probably not work on such a handle, since it expects normal FILE pointers.

like image 40
shartte Avatar answered Oct 15 '22 18:10

shartte