Home > Articles

This chapter is from the book

4.13 Objects-Natural Case Study: Using the miniz-cpp Library to Write and Read ZIP files7

Perf speed.jpg Data compression reduces the size of data—typically to save memory, to save secondary storage space or to transmit data over the Internet faster by reducing the number of bytes. Lossless data-compression algorithms compress data in a manner that does not lose information—the data can be uncompressed and restored to its original form. Lossy data-compression algorithms permanently discard information. Such algorithms are often used to compress images, audio and video. For example, when you watch streaming video online, the video is often compressed ahead of time using a lossy algorithm to minimize the total bytes transferred over the Internet. Though some of the video data is discarded, a lossy algorithm compresses the data in a manner such that most people do not notice the removed information as they watch the video. The video quality is still “pretty good.”

ZIP Files

You’ve probably used ZIP files—if not, you almost certainly will. The ZIP file format8 is a lossless compression9 format that has been in use for over 30 years. Lossless compression algorithms use various techniques for compressing data—such as

  • replacing duplicate patterns, such as text strings in a document or pixels in an image, with references to a single copy, and

  • replacing a group of image pixels that have the same color with one pixel of that color and a count (known as “run-length encoding”).

ZIP is used to compress files and directories into a single file, known as an archive file. ZIP files are often used to distribute software faster over the Internet. Today’s operating systems typically have built-in support for creating ZIP files and extracting their contents.

Open-Source miniz-cpp Library

Many open-source libraries support programmatic manipulation of ZIP archive files and other popular archive-file formats, such as TAR, RAR and 7-Zip.10 Figure 4.11 continues our Objects-Natural presentation by using objects of the open-source miniz-cpp11, 12 library’s class zip_file to create and read ZIP files. The miniz-cpp library is a “header-only library”—it’s defined in header file zip_file.hpp, which you can simply place in the same folder as this example and include the header in your program (line 5). We provide the library in the examples folder’s libraries/miniz-cpp subfolder. Header files are discussed in depth in Chapter 9.

 1   // fig04_11.cpp
 2   // Using the miniz-cpp header-only library to write and read a ZIP file.
 3   #include <iostream>
 4   #include <string>
 5   #include "zip_file.hpp"
 6   using namespace std;
 7

Fig. 4.11 Using the miniz-cpp header-only library to write and read a ZIP file.

Inputting a Line of Text from the User with getline

The getline function call reads all the characters you type until you press Enter:

 8   int main() {
 9      cout << "Enter a ZIP file name: ";
10      string zipFileName;
11      getline(cin, zipFileName); // inputs a line of text
12
Enter a ZIP file name: c:\users\useraccount\Documents\test.zip

Here we use getline to read from the user the location and name of a file, and store it in the string variable zipFileName. Like class string, getline requires the <string> header and belongs to namespace std.

Creating Sample Content to Write an Individual File in the ZIP File

The following statement creates a lengthy string named content consisting of sentences from this chapter’s introduction:

13   // string literals separated only by whitespace are combined
14   // into a single string by the compiler
15   string content{
16       "This chapter introduces all but one of the remaining control "
17       "statements--the for, do...while, switch, break and continue "
18       "statements. We explore the essentials of counter-controlled "
19       "iteration. We use compound-interest calculations to begin "
20       "investigating the issues of processing monetary amounts. First, "
21       "we discuss the representational errors associated with "
22       "floating-point types. We use a switch statement to count the "
23       "number of A, B, C, D and F grade equivalents in a set of "
24       "numeric grades. We show C++17's enhancements that allow you to "
25       "initialize one or more variables of the same type in the "
26      "headers of if and switch statements."};
27

We’ll use the miniz-cpp library to write this string as a text file that will be compressed into a ZIP file. Each string literal in the preceding statement is separated from the next only by whitespace. The C++ compiler automatically assembles such string literals into a single string literal, which we use to initialize the string variable content. The following statement outputs the length of content (632 bytes).

28      cout << "\ncontent.length(): " << content.length();
29
content.length(): 632

Creating a zip_file Object

The miniz-cpp library’s zip_file class—located in the library’s miniz_cpp namespace—is used to create a ZIP file. The statement

30      miniz_cpp::zip_file output; // create zip_file object
31

creates the zip_file object output, which will perform the ZIP operations to create the archive file.

Creating a File in the zip_file Object and Saving That Object to Disk

Line 33 calls output’s writestr member function, which creates one file ("intro.txt") in the ZIP archive containing the text in content. Line 34 calls output’s save member function to store the output object’s contents in the file specified by zipFileName:

32      // write content into a text file in output
33      output.writestr("intro.txt", content); // create file in ZIP
34      output.save(zipFileName); // save output to zipFileName
35

ZIP Files Appear to Contain Random Symbols

ZIP is a binary format, so if you open the compressed file in a text editor, you’ll see mostly gibberish. Below is what the file looks like in the Windows Notepad text editor:

Reading the Contents of the ZIP File

You can locate the ZIP file on your system and extract (decompress) its contents to confirm that the ZIP file was written correctly. The miniz-cpp library also supports reading and processing a ZIP file’s contents programmatically. The following statement creates a zip_file object named input and initializes it with the name of a ZIP file:

36      miniz_cpp::zip_file input{zipFileName}; // load zipFileName
37

This reads the corresponding ZIP archive’s contents. We can then use the zip_file object’s member functions to interact with the archived files.

Displaying the Name and Contents of the ZIP File

The following statements call input’s get_filename and printdir member functions to display the ZIP’s file name and a directory listing of the ZIP file’s contents, respectively.

38      // display input's file name and directory listing
39      cout << "\n\nZIP file's name: " << input.get_filename()
40         << "\n\nZIP file's directory listing:\n";
41      input.printdir();
42
ZIP file's name: c:\users\useraccount\Documents\test.zip
ZIP file's directory listing:
  Length      Date    Time    Name
---------  ---------- -----   ----
      632  11/28/2021 16:48   intro.txt
---------                     -------
      632                     1 file

The output shows that the ZIP archive contains the file intro.txt and that the file’s length is 632, which matches that of the string content we wrote to the file earlier.

Getting and Displaying Information About a Specific File in the ZIP Archive

Line 44 declares and initializes the zip_info object info:

43      // display info about the compressed intro.txt file
44      miniz_cpp::zip_info info{input.getinfo("intro.txt")};
45

Calling input’s getinfo member function returns a zip_info object (from namespace miniz_cpp) for the specified file in the archive. Sometimes objects expose data so that you can access it directly using the object’s name and a dot (.) operator. For example, the object info contains information about the archive’s intro.txt file, including the file’s name (info.filename), its uncompressed size (info.file_size) and its compressed size (info.compress_size):

46      cout << "\nFile name: " << info.filename
47         << "\nOriginal size: " << info.file_size
48         << "\nCompressed size: " << info.compress_size;
49
File name: intro.txt
Original size: 632
Compressed size: 360

Note that intro.txt’s compressed size is 360 bytes—43% smaller than the original file. Compression amounts vary considerably, based on the type of content being compressed.

Extracting "intro.txt" and Displaying Its Original Contents

You can extract the original contents of a compressed file from the ZIP archive. Here we use the input object’s read member function, passing the zip_info object (info) as an argument. This returns as a string the contents of the file represented by the object info:

50   // original file contents
51   string extractedContent{input.read(info)};
52

We output extractedContent to show that it matches the original string content that we “zipped up.” This was indeed a lossless compression:

53      cout << "\n\nOriginal contents of intro.txt:\n"
54         << extractedContent << "\n";
55   }
Original contents of intro.txt:
This chapter introduces all but one of the remaining control statements--the
for, do...while, switch, break and continue statements. We explore the
essentials of counter-controlled iteration. We use compound-interest
calculations to begin investigating the issues of processing monetary
amounts. First, we discuss the representational errors associated with
floating-point types. We use a switch statement to count the number of A, B,
C, D and F grade equivalents in a set of numeric grades. We show C++17's
enhancements that allow you to initialize one or more variables of the same
type in the headers of if and switch statements.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020