C Program to Read and Print All Files From a Zip File
To understand how to write a C program for reading and printing zip files, it’s important to know what exactly a zip file is.
- At its core, a zip file contains one or more files compressed using specific compression algorithms.
- Including the compressed data of the files, the zip file contains meta and header information about all files inside the zip file. These contain file names, modification dates, signatures, compression methods, etc.
- A zip file can also be called a zip archive because of its organization and structure of multiple files.
With the above information in mind we only need two things to programmatically read and print the contents of a zip file:
- A decompression method that will decompress the data so that we can read it.
- A library for interacting with zip files, to make things way easier
We will be using two libraries that also provide decompression functions to write this program.
Library 1: libzip
Library 2: zlib
Both of these libraries are prerequisites for running the code. Libzip is a higher-level library that already utilizes parts of zlib. Zlib is lower level and therefore more technical to use. There will be code examples, one that uses libzip, and one that uses libzip for zip file interaction while utilizing zlib for the decompression.
If these libraries are installed, you can successfully compile them with gcc, just pass compiler flags -lz for method 1 and -lz -lzip for method 2.
Method 1: Reading and Printing All Files from a Zip File using libzip
Example output where my zip file contained this C file
Method 2: Using Zlib Implementation
Zlib cannot directly access zip files, which is why we will use libzip to open the zip file. Zlib directly is used for decompression of the file contents in this method.
Here is the output of the above code using a zip file with 2 files contained