Experience ~ Use Zlib Library to extract zip files

Source: Internet
Author: User
Tags function definition

Recently, in completing a project, you need to use the C + + language to read the contents of a specified file within a zip file. A lot of information on the Internet, in response to the problems encountered in the process, I also studied a bit, is now the method of record down.

On the way to extract the file, according to the information on the Internet, there are probably the following three ways: Call Rar.exe and other external programs. Use a third party class library. Write your own decompression method.

The first way, personal feeling is not very reliable, give up. The third method, I confused the zip compression algorithm, coupled with the temporary need to do this kind of research, give up. Direct copycat, with the second.

The third party class library chooses the famous zlib, the official website is http://www.zlib.net/, I was downloaded from the http://www.winimage.com/zLibDll/index.html, 1.2.5 edition.

In this need to explain a point, if you use visual Studio, only need to download zlib source code, you need to run to generate dynamic library files; If you do not want to be too troublesome, or only vc++6.0, you need to download the dynamic library files. I only vc++6.0 on the machine, so directly to the source code and dynamic library files are downloaded, if you want to compile your own build, you can refer to http://blog.sina.com.cn/s/blog_659b2b3201013y9k.html.

Once the download is complete, you can use the Zlib library.

Pre-use configuration of the Zlib library

Zlib library in use, not simply directly include, you need some configuration.

Since I just use the simple decompression function, I only need the following files:

Zlib-1.2.5\zlib.h

Zlib-1.2.5\zconf.h

Zlib-1.2.5\contrib\minizip\unzip.h

Zlib-1.2.5\contrib\minizip\unzip.c

Zlib-1.2.5\contrib\minizip\ioapi.h

Zlib-1.2.5\contrib\minizip\ioapi.c

I built a zlib folder in the engineering directory and copied the files into it. If you encounter a missing header file in the process of compiling, add the corresponding zlib library file to the error message.

Next, the dynamic library files are also copied in, namely Zlibwapi.lib files and Zlibwapi.dll files.

Then, where you need to use the zlib, add the following code:

#define ZLIB_WINAPI
#include "zlib/unzip.h"

Note that preprocessing definitions and dynamic libraries are required, otherwise link will be faulted. I also studied for a long time to finish, I do not know if you have encountered this problem.

Here's another way to load preprocessing and dynamic libraries. Take vc++6.0 as an example. Open Project-> settings, select the C + +-> general, add Zlib_winapi in preprocessor definitions, then select Link-> Input, Obje Add Zlib/zlibwapi.lib to ct/library modules and Additional library path;

This allows you to use only the Include header file.

In addition, if you run the program, you encounter the following error:

This program cannot be started because Zlibwapi.dll is missing from the computer. Try reinstalling the program to resolve this issue.

Just copy the Zlibwapi.dll file to the Windows\System directory under the system directory.

Extract files using zlib

For the Zlib function definition, the concrete use method and so on, the on-line material is many. Zlib's source code also provides the use of examples, interested friends can study. I'm only here to introduce myself to the relevant methods.

Here's how to open a ZIP file:

Zip file path
char filepath[] = "Aa.zip";

Unzfile Zfile;
Zfile = UnzOpen64 (FILEPATH);
if (Zfile = NULL)
{
	cout << FILEPATH << "File open failed" << Endl;
	return-1;
}

If Zfile is not equal to NULL, it means that the file is open successfully and you can continue with the work that follows.

First, get the global information for the compressed file:

Unz_global_info64 Zglobalinfo;

if (Unz_ok!= unzGetGlobalInfo64 (Zfile, &zglobalinfo))
{
	//error handling
	cout << __file__ << "Medium" << __line__ << Row error, error getting global information. "<< Endl;
	return-1;
}

UNZ_GLOBAL_INFO64 is the structure defined in the Zlib library, where the most important member variable is the number of files in the compressed file. Note that the number of this file does not include the directory.

The following loop iterates through all the files:

Unz_file_info64 Zfileinfo;
unsigned int num = A;
Char *filename = new Char[num];

for (int i = 0; i < zglobalinfo.number_entry i++)
{
	//traverse All Files
	if (Unz_ok!= unzGetCurrentFileInfo64 (Zfile, &zfileinfo, fileName, num, NULL, 0, NULL, 0)
	{
		//error handling information
		cout << __file__ << "Medium" << __l ine__ << Row error, error getting current file information. "<< Endl;
	}
	Unzgotonextfile (Zfile);
}

extern int Zexport unzGetCurrentFileInfo64 of (unzfile file,
                         unz_file_info64 *pfile_info,
                         Char *szfilename,
                         ULong filenamebuffersize,
                         void *extrafield,
                         uLong extrafieldbuffersize,
                         Char *szcomment,
                         ULong commentbuffersize));

The function is to get the file information that is currently read in the compressed package. One of the more important roles is to get the file name that is currently being read, returned by the szFileName parameter, which is an array of char types, and the Filenamebuffersize value is the length of the file name that is returned. That is, if the current file name is "Abcdefg.txt" and the Filenamebuffersize value is set to 4, then the last szFileName value is "ABCD". Another point to note is that the file name returned here is the full path, including the directory path.

Unz_file_info64 is also the structure defined in the Zlib library, which holds information about the current file, and the more commonly used member variables are:

ULong Compression_method Compression method

ULong Dosdate Last Modified date

zpos64_t compressed_size Compressed file size, by number of bytes

zpos64_t uncompressed_size The original file size, the size of the extracted file, by the number of bytes

ULong size_filename filename Length

Gets the information for the current file, and then you can extract the contents of the file:

if (Unz_ok!= unzopencurrentfile (zfile))
{
	//error handling information
	cout << __file__ << "Medium" << __line__ & lt;< "Row error; failed to open the" << fileName << "file in the compressed package. "<< Endl;
}
cout << "Compressed file" << fileName << "content is:" << Endl;
int filelength = zfileinfo.uncompressed_size;
Char *filedata = new Char[filelength];

int len = 1;
while (len)
{
	//uncompressed file
	len = Unzreadcurrentfile (Zfile, (VOIDP) filedata, fileLength-1);
	Filedata[len] = ' the ';
	for (int j = 0; J < Len; j +)
	{
		file.push_back (filedata[j])
	;
}
for (int j = 0; J < File.size (); j + +)
{
	cout << file[j];
}
Unzclosecurrentfile (zfile);
Free (filedata);

The current file is opened through the function Unzopencurrentfile, then the current file information is read through the function Unzreadcurrentfile, and the current file needs to be closed after the related processing completes.

extern int Zexport Unzreadcurrentfile of (unzfile file,
                      voidp buf,
                      unsigned len);

This function means that the contents of the current file are read in bytes by the length of Len, saved to buf, and the number of bytes actually read is returned. In other words, if the current file size is 95 bytes, given len = 10, only 10 bytes of data will be read at a time to save to buf, and the function returned 10 each time. And the last read, although also read 10 bytes of data, but the file has only 5 bytes of data has not been read, then the final return result is 5.

Therefore, when actually reading the file, you can read all the contents of the file at once according to the value of the zfileinfo.uncompressed_size variable in the current file information, or read the content of different lengths according to different requirements.

If in the current zip file, only need the content of a file, but also know the specific file name, you can not through the loop, directly navigate to the desired file.

Char *filename = "Aa.txt";
if (Unz_ok = = Unzlocatefile (zfile, FileName, 0))
{
	//file processing
}

It is important to note that the file name passed in here must be a full path including the directory path, otherwise it will not be searched.

extern int Zexport unzlocatefile of ((unzfile file,
                     const char *szfilename,
                     int icasesensitivity));

The icasesensitivity parameter in this function represents file matching, 1 is case-sensitive, 2 is case-insensitive, and 0 is determined according to the operating system, and is not differentiated under Windows.

Finally, you need to call

Unzclose (Zfile)

Closes the open zip file. Also, don't forget to release the memory of the related variables.

PostScript

This article simply records the use of the zlib used in your own project, and does not do more in-depth research. And because of the project requirements, I have not studied how to compress files through the Zlib library for the time being. If friends are interested in this area, you can search the relevant information on the Internet, their own research, or relatively simple.

If there is anything wrong in the article, you are welcome to correct your point.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.