Click here to Skip to main content
Click here to Skip to main content

XZip and XUnzip - Add zip and/or unzip to your app with no extra .lib or .dll

By , 18 Jul 2007
 

Introduction

I have already introduced XZip in a previous article. This article presents XZip and also XUnzip, which together allow you to add zip and unzip to your application without using any .lib or .dll.

First, let me acknowledge the work of Lucian Wischik, who took the many .c and .h files from Info-ZIP and produced the .cpp and .h files that XZip is based on.

XZip and XUnzip Features

Most of the functions are demonstrated in the XZip demo app. Here are the main ones:

  • CreateZip() - Create a zip archive file.
//////////////////////////////////////////////////////////////////////////////
//
// CreateZip()
//
// Purpose:     Create a zip archive file
//
// Parameters:  z     - archive file name if flags is ZIP_FILENAME;  for other
//                       uses see below
//              len   - for memory (ZIP_MEMORY) should be the buffer size;
//                       for other uses, should be 0
//              flags - indicates usage, see below;  for files, this will be
//                       ZIP_FILENAME
//
// Returns:     HZIP  - non-zero if zip archive created ok, otherwise 0
//
  • ZipAdd() - Add a file to a zip archive.
//////////////////////////////////////////////////////////////////////////////
//
// ZipAdd()
//
// Purpose:     Add a file to a zip archive
//
// Parameters: hz      - handle to an open zip archive
//             dstzn   - name used inside the zip archive to identify the file
//             src     - for a file (ZIP_FILENAME) this specifies the filename
//                        to be added to the archive;  for other uses, see 
//                        below
//             len     - for memory (ZIP_MEMORY) this specifies the buffer
//                        length;  for other uses, this should be 0
//             flags   - indicates usage, see below;  for files, this will be
//                        ZIP_FILENAME
//
// Returns:    ZRESULT - ZR_OK if success, otherwise some other value
//
  • OpenZip() - Open an existing zip archive file.
//////////////////////////////////////////////////////////////////////////////
//
// OpenZip()
//
// Purpose:     Open an existing zip archive file
//
// Parameters:  z      - archive file name if flags is ZIP_FILENAME;  for 
//                        other uses see below
//              len    - for memory (ZIP_MEMORY) should be the buffer size;
//                       for other uses, should be 0
//              flags  - indicates usage, see below;  for files, this will be
//                       ZIP_FILENAME
//
// Returns:     HZIP   - non-zero if zip archive opened ok, otherwise 0
//
  • GetZipItem() - Get information about an item in an open zip archive.
//////////////////////////////////////////////////////////////////////////////
//
// GetZipItem()
//
// Purpose:     Get information about an item in an open zip archive
//
// Parameters:  hz      - handle of open zip archive
//              index   - index number (0 based) of item in zip
//              ze      - pointer to a ZIPENTRY (if ANSI) or ZIPENTRYW struct
//                        (if Unicode)
//
// Returns:     ZRESULT - ZR_OK if success, otherwise some other value
//
  • FindZipItem() - Find item by name and return information about it.
//////////////////////////////////////////////////////////////////////////////
//
// FindZipItem()
//
// Purpose:     Find item by name and return information about it
//
// Parameters:  hz      - handle of open zip archive
//              name    - name of file to look for inside zip archive
//              ic      - TRUE = case insensitive
//              index   - pointer to index number returned, or -1
//              ze      - pointer to a ZIPENTRY (if ANSI) or ZIPENTRYW struct
//                        (if Unicode)
//
// Returns:     ZRESULT - ZR_OK if success, otherwise some other value
//
  • UnzipItem() - Find item by index and unzip it.
//////////////////////////////////////////////////////////////////////////////
//
// UnzipItem()
//
// Purpose:     Find item by index and unzip it
//
// Parameters:  hz      - handle of open zip archive
//              index   - index number of file to unzip
//              dst     - target file name of unzipped file
//              len     - for memory (ZIP_MEMORY. length of buffer;
//                        otherwise 0
//              flags   - indicates usage, see below;  for files, this will be
//                        ZIP_FILENAME
//
// Returns:     ZRESULT - ZR_OK if success, otherwise some other value
//
  • CloseZip() - Close an open zip archive.
//////////////////////////////////////////////////////////////////////////////
//
// CloseZip()
//
// Purpose:     Close an open zip archive
//
// Parameters:  hz      - handle to an open zip archive
//
// Returns:     ZRESULT - ZR_OK if success, otherwise some other value
//

How To Use

To integrate XZip into your app, you first need to add following the files to your project:

  • XZip.cpp
  • XZip.h
  • XUnzip.cpp
  • XUnzip.h

If you include XZip in a project that uses precompiled headers, you must change C/C++ Precompiled Headers settings to Not using precompiled headers for XZip.cpp and XUnzip.cpp.

Next, include the header files XZip.h and XUnzip.h in appropriate project files. Now you are ready to start using XZip. There are many notes concerning usage of various functions in XZip.h and XUnzip.h. Please read all function headers for each function you wish to use.

Known Limitations

XZip and XUnzip have been tested only with files.

Demo App

The XZipTest.exe demo tests the APIs in XZip and XUnzip. Here is some of the output:

screenshot

Frequently Asked Questions

  1. Can I use XZip in non-MFC apps?
    Yes. It has been implemented to compile with any Win32 program.
  2. When I try to include XZip.cpp in my MFC project, I get the compiler error XZip.cpp(2918) : fatal error C1010: unexpected end of file while looking for precompiled header directive. How can I fix this?
    When using XZip in project that uses precompiled headers, you must change C/C++ Precompiled Headers settings to Not using precompiled headers for XZip.cpp and XUnzip.cpp. Be sure to do this for All Configurations.

screenshot


  1. When I try to build the demo app, I get the linker error LINK : fatal error LNK1104: cannot open file "mfc42u.lib" Error executing link.exe. How can I fix this?
    The default installation options of Visual C++ v6.0 don't install the Unicode libraries of MFC, so you might get an error that mfc42u.lib or mfc42ud.lib cannot be found. You can fix this either by installing the Unicode libs from the VC++ install CD, or by going to Build | Set Active Configuration and selecting one of the non-Unicode configurations.

    screenshot

    You can configure the Visual Studio toolbars to include the Select Active Configuration combobox. This allows you to see at a glance what configuration you are working with.

  2. I don't need the Zip/Unzip functions. Can I exclude XZip.cpp/XUnzip.cpp?
    Yes. You only need to include the .h/.cpp pair that you need.
  3. Can we use XZip in our (shareware/commercial) app?
    Yes, you can use XZip without charge or license fee, providing you follow the Info-ZIP restrictions as defined in XZip.cpp.
  4. Does XZip handle pipes? in-memory zipping?
    XZip has not been tested with anything other than files.
  5. Can I use XZip in a VS2005 project?
    Yes. There is a sample VS2005 project included in the download.
  6. Does XZip work on Vista?
    Yes.

Acknowledgments

Revision History

Version 1.3 - 2007 July 18

  • Fixed problem with file size that is multiple of 16384, reported by Mathias Svensson.
  • Fixed XZip to save file time in local time, suggested by Damir Valiulin.

Version 1.2 - 2007 June 30

  • Added project for VS2005.
  • Added AddFolderContent() contributed by Renaud Deysine.
  • Fixed problem with TUnzip::Open() reported by Pete Howells. Open() now returns correct success code.
  • Fixed several bugs reported by Warren Stevens.
  • Fixed a problem in unzReadCurrentFile() reported by Kochise.
  • Fixed bug in EnsureDirectory() reported by craigmj.
  • Changed ideflate() suggested by Michael B. Hansen.
  • Fixed problem with time_t reported by Ronney.
  • Fixed problems found by Boundschecker as reported by Warren Stevens.
  • Made changes to PUTSHORT and PUTBYTE macros and to TZip::write(), suggested by vielheit.

Version 1.1 - 2003 May 7

  • Initial public release

Usage

This software is released into the public domain. You are free to use it in any way you like, except that you may not sell this source code. If you modify it or extend it, please to consider posting new code here for everyone to share. This software is provided "as is" with no expressed or implied warranty. I accept no liability for any damage or loss of business that this software may cause.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Hans Dietrich
Software Developer (Senior) Hans Dietrich Software
United States United States
Member
I attended St. Michael's College of the University of Toronto, with the intention of becoming a priest. A friend in the University's Computer Science Department got me interested in programming, and I have been hooked ever since.
 
Recently, I have moved to Los Angeles where I am doing consulting and development work.
 
For consulting and custom software development, please see www.hdsoft.org.






Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionEnsureDirectory leaves temp directories [modified]memberMarkus Bst13 Mar '13 - 2:24 
Hello everyone,
 
first of all: thanks for this piece of code, it is really helpful and easy to use.Thumbs Up | :thumbsup:
 
I unzipped a file containing subfolders. I noticed, that the function
void EnsureDirectory(const TCHAR *rootdir, const TCHAR *dir)
creates the subfolder structure in the current working directory as well as in the target folder. Those temporary directories are not cleaned up afterwards.
 
As a quick fix, I removed the
CreateDirectory(cd,NULL)
call.
My tests still run, everything gets extracted correctly.
Does anyone have a similar experience? Did I forget something?
 
[Edit]
My tests run, because I didn't expect the Unzip-function to create subfolders. I do this before I call Unzip, that's why it works.
However, rootdir is set to
GetCurrentDirectory(MAX_PATH,rootdir);
when opening the zipfile. It is used in
TUnzip::Unzip(...)
 
As a bugfix I removed the EnsureDirectoryMethod and create the subfolder structure before I call Unzip on an item.
 
Best regards,
Markus
 
P.S.
Environment: Windows7, VS2010 SP1

modified 14 Mar '13 - 3:49.

GeneralReally useful jobmemberzirandeai25 Feb '13 - 18:53 
really useful,many thanks.
QuestionCString with path and file name [modified]memberMike Gaskey21 Jan '13 - 7:11 
I've tried everything I can think of but I cannot get the logic to accept anything other than a lliteral as in "some file name" as input for a file to be added to a just created zip file. I have the full path and file name in a CString object and have tried several ways of specifying including (void *)&MyCString for the 3rd parameter of the ZipAdd() function but it always fails. Any idea?
 
oh well. Shortly after I posted the above I found the solution to my problem:
CString wcString = "Whatever the full path and file name happen to be";
 
Then:
wcString.GetBuffer() <-- as the 3rd paramter to ZipAdd() works.
Mike - typical white guy.
 
"Political correctness is a doctrine, fostered by a delusional, illogical minority, and rabidly promoted by an unscrupulous mainstream media, which holds forth the proposition that it is entirely possible to pick up a piece of sh*t by the clean end."
 
Thomas Mann - "Tolerance becomes a crime when applied to evil."
 
As American as: hot dogs, apple and Sarah Palin.


modified 21 Jan '13 - 13:52.

QuestionBugs found and fixed.memberluuxuanduan8 Nov '12 - 23:12 
Hi guys,

Thanks for the code. I've tried it and has found and fixed 2 bugs:
1. In BOOL AddFolderContent(HZIP hZip, TCHAR* AbsolutePath, TCHAR* DirToAdd) (it didn't work):

I've fixed as follows:
 
//Duan fixed bug
CString stPath;
stPath = AbsolutePath;
stPath += RelativePathNewFileFound;
if (ZipAdd(hZip, RelativePathNewFileFound, /*RelativePathNewFileFound*/(TCHAR*)((LPCTSTR)stPath), 0, ZIP_FILENAME) != ZR_OK)
{
return FALSE;
}
 

2. Bug for Unicode mode for adding a folder in a zip: In ZRESULT ZipAdd(HZIP hz, const TCHAR *dstzn, void *src, unsigned int len, DWORD flags)

I've fixed as follows:
 
//Duan added || flags == ZIP_FOLDER
if (flags == ZIP_FILENAME || flags == ZIP_FOLDER)
{
char szDest[MAX_PATH*2];
memset(szDest, 0, sizeof(szDest));

#ifdef _UNICODE
// need to convert Unicode dest to ANSI
int nActualChars = WideCharToMultiByte(CP_ACP, // code page
0, // performance and mapping flags
(LPCWSTR) dstzn, // wide-character string
-1, // number of chars in string
szDest, // buffer for new string
MAX_PATH*2-2, // size of buffer
NULL, // default for unmappable chars
NULL); // set when default char used
if (nActualChars == 0)
return ZR_ARGS;
#else
strcpy(szDest, dstzn);
#endif

lasterrorZ = zip->Add(szDest, src, len, flags);
}
else
{
lasterrorZ = zip->Add((char *)dstzn, src, len, flags);
}
 

Best Regards,
Duan.
SuggestionFindZipItem support Windows RelativePath [modified]memberdaviyang9 Apr '12 - 0:56 
Windows system using this code find subdirectory file didn't work
FindZipItem(hz, _T("toolbar\\bk.bmp"), true, &i, &ze)
 
change code,work well
int unzLocateFile (unzFile file, const TCHAR *szFileName, int iCaseSensitivity)
{
	unz_s* s;
	int err;
 
	uLong num_fileSaved;
	uLong pos_in_central_dirSaved;
 
	if (file==NULL)
		return UNZ_PARAMERROR;
 
    if (_tcslen(szFileName)>=UNZ_MAXFILENAMEINZIP)
        return UNZ_PARAMERROR;
 
	char szFileNameA[MAX_PATH];
 
#ifdef _UNICODE
	GetAnsiFileName(szFileName, szFileNameA, MAX_PATH-1);
#else
	strcpy(szFileNameA, szFileName);
#endif
 
	// support Windows subdirectory
	int iLen=strlen(szFileNameA);
	for (int i=0;i<iLen;i++)
	{
		if (szFileNameA[i]=='\\')
		{
			szFileNameA[i]='/';
		}
	}
 
	s=(unz_s*)file;
	if (!s->current_file_ok)
		return UNZ_END_OF_LIST_OF_FILE;
 
	num_fileSaved = s->num_file;
	pos_in_central_dirSaved = s->pos_in_central_dir;
 
	err = unzGoToFirstFile(file);
 
	while (err == UNZ_OK)
	{
		char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1];
		unzGetCurrentFileInfo(file,NULL,
								szCurrentFileName,sizeof(szCurrentFileName)-1,
								NULL,0,NULL,0);
		TRACE(_T("%s\t%s"),szCurrentFileName,szFileNameA);
		if (unzStringFileNameCompare(szCurrentFileName,szFileNameA,iCaseSensitivity)==0)
			return UNZ_OK;
		err = unzGoToNextFile(file);
	}
 
	s->num_file = num_fileSaved ;
	s->pos_in_central_dir = pos_in_central_dirSaved ;
	return err;
}


modified 9 Apr '12 - 7:33.

BugWrong file time set in decompressed file in some cases - fixmemberFrank Kobs15 Dec '11 - 0:06 
I found a small bug where the file date and time is not correctly set in unzipped file.
Some zip files do not set the date/time of their contained files at all.
So DOS date / time members are zero.
 
ZRESULT TUnzip::Get(int index,ZIPENTRY *ze)
{ .
  .
  WORD dostime = (WORD)(ufi.dosDate&0xFFFF);
  WORD dosdate = (WORD)((ufi.dosDate>>16)&0xFFFF);
  FILETIME ft;
  DosDateTimeToFileTime(dosdate,dostime,&ft);
  ze->atime=ft; ze->ctime=ft; ze->mtime=ft;
  .
  .
  .
}
 
DosDateTimeToFileTime fails if dostime and and dosdate is zero.
since ft is not initialized, some random values are inside.
 
Better:
Initialize ft with current date time.
ZRESULT TUnzip::Get(int index,ZIPENTRY *ze)
{ .
  .
  WORD dostime = (WORD)(ufi.dosDate&amp;0xFFFF);
  WORD dosdate = (WORD)((ufi.dosDate&gt;&gt;16)&amp;0xFFFF);
  FILETIME ft;
 
  SYSTEMTIME st;
  GetSystemTime(&st);  // Gets the current system time
  SystemTimeToFileTime(&st, &ft);  // Converts the current system time to file time format

  DosDateTimeToFileTime(dosdate,dostime,&amp;ft);
  ze->atime=ft; ze->ctime=ft; ze->mtime=ft;
  .
  .
  .
}
 
but anyway: Thanks for sharing the code!
 
With best regards,
 
Frank Kobs
Palette CAD GmbH
BugBug in TUnzip::Get lets UnzipItem create read-only filesmemberThomas Haase1 Dec '11 - 0:45 
UnzipItem may create wrongly read-only files.
 
I'm calling the function like this:
zr = UnzipItem(hz, index, targetname, 0, ZIP_FILENAME);
 
The problem occurs when working with zip files, that have not been created with XZip.
For example, I have created zip files with
  • Windows-7 Context menu 'Send To' 'Compressed (zipped) Folder'
  • Java
  • Total Commander 7.56a
  • 7-Zip 9.20
In all cases UnzipItem creates wrongly read-only files.
 
The problem is located in TUnzip::Get when evaluating the so called upper half of the attribute value, which is called standard unix attr in the comment.
In the line, that initializes bool uwritable, what does this comment // ***hd*** mean? Does it mean Hans Dietrich?
 
I have temporary solved this issue for my use case by commenting out the evaluation of uwritable
, but I guess this won't work, if I would handle zip files that have been created on a unix machine.
 
Please advice, any comments are welcome.
 
I've already posted this issue in 2003, the problem still exist in the latest Version 1.3.
http://www.codeproject.com/Messages/681420/Problem-in-TUnzip-Get-gt-creates-sometimes-read-on.aspx[^]
Thomas Haase

Question_stricmp / _tzset instead of #pragma warning(disable : 4996)memberThomas Haase30 Nov '11 - 23:24 
Generally I don't like to hide warnings by using a global pragma. But I know, this is my personal preference.
 
But I would like to discuss an alternative solution.
 
In the past we had solved the related issue by by using _stricmp and _tzset instead of stricmp and tzset.
Are there any arguments against this alternative solution?
Thomas Haase

QuestionUpdated version available?memberDale Fugier25 Nov '11 - 12:05 
There has been a lot of fixes and enhancements posted over the years. Is there an updated version that includes all of these fixes?
AnswerRe: Updated version available?memberThomas Haase30 Nov '11 - 22:31 
Yes! Version 1.4 would be very welcome!
Thomas Haase

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 18 Jul 2007
Article Copyright 2003 by Hans Dietrich
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid