viksoe.dk

ZIP Archive classes


This article was submitted .


The ZIP Archive classes allow you to examine and extract files in a compressed ZIP archive.

The classes can enumerate the compressed files stored inside a ZIP file and extract the files one by one. There is nothing really magic about this, because it uses the ZLIB library maintained by Jean-loup Gailly and Mark Adler.

The CZipArchive class gives access to the compressed entries through the GetFile() methods. The uncompressed data is returned in a CZipFile class that can be used as a memory stream.
To enumerate the entries in the ZIP use the FindFirstFile(), FindNextFile() and FindClose() methods. They operate exactly like the Win32 API FindFile counterparts.
The classes cannot compress data, delete, overwrite or add new entries to the ZIP file. It does however support compressed and encrypted ZIP 2.0 files.

So, to open and use a ZIP file, use the following syntax:

  CZipArchive zip;
  zip.Open(_T("test.zip"));
  ...
  zip.Close();
To extract a file from the ZIP archive:
  CZipFile file;
  if( zip.GetFile(_T("readme.txt"), &file) == TRUE ) {
    DWORD dwSize = file.GetSize();
    LPSTR pStr = (LPSTR) _alloca(dwSize);
    file.Read(pStr, dwSize, NULL);
    file.Close();
  }
Enumerate the entries in the ZIP like this:
  ZIP_FIND_DATA fd;
  HANDLE hFD = zip.FindFirstFile(_T("*.*"), &fd);
  if( hFD != INVALID_HANDLE_VALUE ) {
    while( true ) {
      printf(_T("%s"), fd.cFileName);
      if( zip.FindNextFile(hFD, &fd) == FALSE ) break;
    }
    zip.FindClose(hFD);
  }
If you're dealing with an archive containing encrypted files, call the SetPassword method on CZipArchive before you start retrieving files.

Interface

 NameDescription
OpenOpens a ZIP archive.
CloseCloses the archive.
GetFileExtracts a file entry.
SetPasswordSet password to use on encrypted files.
FindFirstFileEnumerates files in ZIP.
FinNextFileGets the next file in FindFirstFile enumeration.
FindCloseCloses the find enumeration.

Notes

The ZLIB library is free - even for commercial use. But please respect the copyright notice in the zlib.h file. ZLIB is compatible with both PKZIP and WINZIP.

Source Code Dependencies

Microsoft Visual C++ 6.0
Microsoft ATL Library
ZLIB

Useful Links

The ZLIB home

Download Files

DownloadSource Code (6 Kb)
ZLIB files (100 Kb)

To the top