hitcounter
dpointer
Monday, November 21, 2005
 
Simple Unzip

How to extract files from a ZIP file? Simple. The code fragment below shows how to do it. You need to have zlib for the decompression routine and minizip for the actual ZIP-compatible implementation. Note that minizip package already contains a full implementation of unzip, called mini-unzip, yet the function presented here is simpler to understand and to modify.

To compile, you need to link to libzlib and few files from minizip (unzip.c and ioapi.c, also iowin32.c in Windows). The function is self-explained, it will extract filename inside the zipfile (must be a valid ZIP) and write it to outfile. If outfile already exists, it will be overwritten. Note that error handling is minimal to make the code readable.

This code is BSD licensed.

#include "unzip.h"

#define UNZIP_OK 0
#define UNZIP_ERROPEN 1
#define UNZIP_ERRNOTFOUND 2
#define UNZIP_ERRCREATE 3
#define UNZIP_ERRREAD 4
#define UNZIP_ERRWRITE 5

int unzipFile( char* zipfile, char* filename, char* outfile )
{
  unzFile uf = 0;
  FILE* fout = 0;
  int result, bytes;
  char buffer[1024];

  uf = unzOpen( zipfile );
  if( !uf )
  {
    printf( "Can not open file '%s' !\n", zipfile );
    return UNZIP_ERROPEN;
  }

  if( unzLocateFile( uf, filename, 0 ) != UNZ_OK )
  {
    printf( "Can not find '%s' inside the zipfile !\n", filename );
    unzCloseCurrentFile(uf);
    return UNZIP_ERRNOTFOUND;
  }
  
  if( unzOpenCurrentFile( uf) != UNZ_OK )
  {
    printf( "Can not open '%s' inside the zipfile !\n", filename );
    unzCloseCurrentFile(uf);
    return UNZIP_ERRNOTFOUND;
  }

  fout = fopen( outfile,"wb" );
  if( !fout )
  {
    printf( "Can not create file '%s' !\n", outfile );
    unzCloseCurrentFile(uf);
    return UNZIP_ERRCREATE;
  }

  result = UNZIP_OK;
  for(;;)
  {
    bytes = unzReadCurrentFile( uf, buffer, sizeof(buffer) );
    if( bytes == 0 ) break; /* finish */
    if( bytes < 0 )
    {
      printf( "Error reading %s %d!\n", filename, bytes );
      result = UNZIP_ERRREAD;
      break;
    }
    else
      if( fwrite( buffer, 1, bytes, fout )!= bytes )
      {
        printf("error in writing extracted file\n");
        result = UNZIP_ERRWRITE;
        break;
      }
  }
  
  fclose( fout );
  unzCloseCurrentFile( uf );

  return result;
}


Powered by Blogger