std.zip

Read and write data in the zip archive format.

Members

Classes

ArchiveMember
class ArchiveMember

A single file or directory inside the archive.

ZipArchive
class ZipArchive

Object representing the entire archive. ZipArchives are collections of ArchiveMembers.

ZipException
class ZipException

Thrown on error.

Enums

CompressionMethod
enum CompressionMethod

Compression method used by ArchiveMember.

Examples

Example for reading an existing zip archive:

import std.stdio : writeln, writefln;
import std.file : read;
import std.zip;

void main(string[] args)
{
    // read a zip file into memory
    auto zip = new ZipArchive(read(args[1]));

    // iterate over all zip members
    writefln("%-10s  %-8s  Name", "Length", "CRC-32");
    foreach (name, am; zip.directory)
    {
        // print some data about each member
        writefln("%10s  %08x  %s", am.expandedSize, am.crc32, name);
        assert(am.expandedData.length == 0);

        // decompress the archive member
        zip.expand(am);
        assert(am.expandedData.length == am.expandedSize);
    }
}

Example for writing files into a zip archive:

import std.file : write;
import std.string : representation;
import std.zip;

void main()
{
    // Create an ArchiveMembers for each file.
    ArchiveMember file1 = new ArchiveMember();
    file1.name = "test1.txt";
    file1.expandedData("Test data.\n".dup.representation);
    file1.compressionMethod = CompressionMethod.none; // don't compress

    ArchiveMember file2 = new ArchiveMember();
    file2.name = "test2.txt";
    file2.expandedData("More test data.\n".dup.representation);
    file2.compressionMethod = CompressionMethod.deflate; // compress

    // Create an archive and add the member.
    ZipArchive zip = new ZipArchive();

    // add ArchiveMembers
    zip.addMember(file1);
    zip.addMember(file2);

    // Build the archive
    void[] compressed_data = zip.build();

    // Write to a file
    write("test.zip", compressed_data);
}

Meta

Standards

The current implementation mostly conforms to ISO/IEC 21320-1:2015, which means,

  • that files can only be stored uncompressed or using the deflate mechanism,
  • that encryption features are not used,
  • that digital signature features are not used,
  • that patched data features are not used, and
  • that archives may not span multiple volumes.

Additionally, archives are checked for malware attacks and rejected if detected. This includes

  • zip bombs which generate gigantic amounts of unpacked data
  • zip archives that contain overlapping records
  • chameleon zip archives which generate different unpacked data, depending on the implementation of the unpack algorithm

The current implementation makes use of the zlib compression library.

Usage:

There are two main ways of usage: Extracting files from a zip archive and storing files into a zip archive. These can be mixed though (e.g. read an archive, remove some files, add others and write the new archive).