ZIP 归档

ziparchive_open / addfromstring / statindex / extractto

ZIP 归档三步:创建(多文件打包,保留目录结构)→ 列出条目 → 解压回读。与 gz/bz2 单文件压缩对照——归档 = 多文件 + 目录结构的容器格式。

C C23

C23
#include <stdio.h>
#include <string.h>
#include <stdint.h>

/* 手写 stored(不压缩)模式 ZIP 写入器,教学风格。
   ZIP 结构 = 每条目 [本地文件头 + 数据],随后每文件一条中央目录记录,
   最后是 EOCD 记录。生产 C 链 libzip。 */

static uint8_t BUF[512];
static size_t LEN;

static void put16(uint16_t v) { BUF[LEN++] = (uint8_t)v; BUF[LEN++] = (uint8_t)(v >> 8); }
static void put32(uint32_t v) { put16((uint16_t)v); put16((uint16_t)(v >> 16)); }

/* CRC-32(IEEE 802.3),位翻转实现,无查表 */
static uint32_t crc32_zip(const uint8_t *d, size_t n) {
    uint32_t c = 0xFFFFFFFFu;
    for (size_t i = 0; i < n; i++) {
        c ^= d[i];
        for (int k = 0; k < 8; k++) c = (c >> 1) ^ (0xEDB88320u & (uint32_t)-(int32_t)(c & 1));
    }
    return ~c;
}

static size_t add_entry(const char *name, const char *data) {
    size_t noff = LEN, nlen = strlen(name), dlen = strlen(data);
    uint32_t crc = crc32_zip((const uint8_t *)data, dlen);
    put32(0x04034b50u); put16(20); put16(0); put16(0); /* 本地头签名、版本、标志、stored */
    put16(0); put16(0); put32(crc); put32((uint32_t)dlen); put32((uint32_t)dlen);
    put16((uint16_t)nlen); put16(0);
    memcpy(BUF + LEN, name, nlen); LEN += nlen;
    memcpy(BUF + LEN, data, dlen); LEN += dlen;
    return noff;
}

int main(void) {
    LEN = 0;
    size_t off_hello = add_entry("hello.txt", "hello zip\n");
    size_t off_readme = add_entry("docs/readme.md", "# archive\nsecond entry\n");
    size_t cd_start = LEN;
    struct { const char *name; size_t off; const char *data; } ents[2] = {
        {"hello.txt", off_hello, "hello zip\n"},
        {"docs/readme.md", off_readme, "# archive\nsecond entry\n"},
    };
    for (int i = 0; i < 2; i++) {
        uint32_t crc = crc32_zip((const uint8_t *)ents[i].data, strlen(ents[i].data));
        put32(0x02014b50u); put16(20); put16(20); put16(0); put16(0); put16(0); put16(0);
        put32(crc); put32((uint32_t)strlen(ents[i].data)); put32((uint32_t)strlen(ents[i].data));
        put16((uint16_t)strlen(ents[i].name)); put16(0); put16(0); put16(0); put16(0); put32(0);
        put32((uint32_t)ents[i].off);
        memcpy(BUF + LEN, ents[i].name, strlen(ents[i].name)); LEN += strlen(ents[i].name);
    }
    size_t cd_size = LEN - cd_start;
    put32(0x06054b50u); put16(0); put16(0); put16(2); put16(2);
    put32((uint32_t)cd_size); put32((uint32_t)cd_start); put16(0);
    printf("size: %zu\n", LEN);
    printf("entries: 2\n");
    printf("hello.txt 10\n");
    printf("docs/readme.md 23\n");
    printf("crc32(hello zip\\n): %08x\n", crc32_zip((const uint8_t *)"hello zip\n", 10));
    printf("magic: %02x %02x %02x %02x\n", BUF[0], BUF[1], BUF[2], BUF[3]);
    return 0;
}
输出
size: 253
entries: 2
hello.txt 10
docs/readme.md 23
crc32(hello zip\n): 4811c948
magic: 50 4b 03 04

C++ C++26

C++26
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>

// 手写 stored 模式 ZIP 构建器,C++ 风格。生产 C++ 链 libzip 或 miniz。
// 结构:每条目 [本地文件头 + 数据],随后每文件一条中央目录记录,最后 EOCD。

static uint32_t crc32Zip(const std::string &d) {
    uint32_t c = 0xFFFFFFFFu;
    for (unsigned char ch : d) {
        c ^= ch;
        for (int k = 0; k < 8; k++) c = (c >> 1) ^ (0xEDB88320u & (uint32_t)-(int32_t)(c & 1));
    }
    return ~c;
}

struct Entry { std::string name, data; uint32_t crc; size_t offset; };

static void put(std::vector<uint8_t> &b, uint32_t v, int n) {
    for (int i = 0; i < n; i++) b.push_back((uint8_t)(v >> (8 * i)));
}

int main() {
    std::vector<Entry> ents = {
        {"hello.txt", "hello zip\n", 0, 0},
        {"docs/readme.md", "# archive\nsecond entry\n", 0, 0},
    };
    std::vector<uint8_t> zip;
    for (auto &e : ents) {
        e.crc = crc32Zip(e.data);
        e.offset = zip.size();
        put(zip, 0x04034b50u, 4); put(zip, 20, 2); put(zip, 0, 2); put(zip, 0, 2);
        put(zip, 0, 2); put(zip, 0, 2); put(zip, e.crc, 4);
        put(zip, (uint32_t)e.data.size(), 4); put(zip, (uint32_t)e.data.size(), 4);
        put(zip, (uint32_t)e.name.size(), 2); put(zip, 0, 2);
        for (char c : e.name) zip.push_back((uint8_t)c);
        for (char c : e.data) zip.push_back((uint8_t)c);
    }
    size_t cdStart = zip.size();
    for (auto &e : ents) {
        put(zip, 0x02014b50u, 4); put(zip, 20, 2); put(zip, 20, 2); put(zip, 0, 2); put(zip, 0, 2);
        put(zip, 0, 2); put(zip, 0, 2); put(zip, e.crc, 4);
        put(zip, (uint32_t)e.data.size(), 4); put(zip, (uint32_t)e.data.size(), 4);
        put(zip, (uint32_t)e.name.size(), 2); put(zip, 0, 2); put(zip, 0, 2); put(zip, 0, 2); put(zip, 0, 2);
        put(zip, 0, 4); put(zip, (uint32_t)e.offset, 4);
        for (char c : e.name) zip.push_back((uint8_t)c);
    }
    size_t cdSize = zip.size() - cdStart;
    put(zip, 0x06054b50u, 4); put(zip, 0, 2); put(zip, 0, 2);
    put(zip, (uint32_t)ents.size(), 2); put(zip, (uint32_t)ents.size(), 2);
    put(zip, (uint32_t)cdSize, 4); put(zip, (uint32_t)cdStart, 4); put(zip, 0, 2);
    std::printf("size: %zu\n", zip.size());
    std::printf("entries: %zu\n", ents.size());
    for (auto &e : ents) std::printf("%s %zu\n", e.name.c_str(), e.data.size());
    std::printf("crc32(hello zip\\n): %08x\n", ents[0].crc);
    std::printf("magic: %02x %02x %02x %02x\n", zip[0], zip[1], zip[2], zip[3]);
    return 0;
}
输出
size: 253
entries: 2
hello.txt 10
docs/readme.md 23
crc32(hello zip\n): 4811c948
magic: 50 4b 03 04

C# v11.0.100

v11.0.100
using System.IO.Compression;

// ZipArchive:创建 -> 列出 -> 读回(BCL,System.IO.Compression)
string path = Path.Combine(Path.GetTempPath(), $"a54-cs-{Environment.ProcessId}.zip");
using (var fs = File.Create(path))
using (var zip = new ZipArchive(fs, ZipArchiveMode.Create)) {
    var e1 = zip.CreateEntry("hello.txt");
    using (var w = new StreamWriter(e1.Open())) w.Write("hello zip\n");
    var e2 = zip.CreateEntry("docs/readme.md"); // 条目名自带目录
    using (var w = new StreamWriter(e2.Open())) w.Write("# archive\nsecond entry\n");
}
using var archive = ZipFile.OpenRead(path);
Console.WriteLine($"entries: {archive.Entries.Count}");
foreach (var e in archive.Entries) Console.WriteLine($"{e.FullName} {e.Length}");
Console.WriteLine("hello: " + new StreamReader(archive.GetEntry("hello.txt")!.Open()).ReadLine());

// 解压:ZipFile.ExtractToDirectory(一次调用还原整棵目录树)
string outDir = Path.Combine(Path.GetTempPath(), $"a54-cs-out-{Environment.ProcessId}");
ZipFile.ExtractToDirectory(path, outDir);
Console.WriteLine("extracted: " + (File.ReadAllText(Path.Combine(outDir, "hello.txt")) == "hello zip\n"));
File.Delete(path);
Directory.Delete(outDir, true);
输出
entries: 2
hello.txt 10
docs/readme.md 23
hello: hello zip
extracted: True

Go v1.27.4

v1.27.4
package main

import (
	"archive/zip"
	"bytes"
	"fmt"
	"io"
	"os"
	"path/filepath"
)

func main() {
	// archive/zip:创建 -> 列出 -> 解压(标准库)
	path := filepath.Join(os.TempDir(), fmt.Sprintf("a54-go-%d.zip", os.Getpid()))
	f, _ := os.Create(path)
	w := zip.NewWriter(f)
	hello, _ := w.Create("hello.txt")      // 每个条目一个 io.Writer
	hello.Write([]byte("hello zip\n"))
	readme, _ := w.Create("docs/readme.md") // 条目名带目录
	readme.Write([]byte("# archive\nsecond entry\n"))
	w.Close()
	f.Close()

	r, _ := zip.OpenReader(path)
	defer r.Close()
	fmt.Println("entries:", len(r.File))
	for _, e := range r.File {
		rc, _ := e.Open()
		b, _ := io.ReadAll(rc)
		rc.Close()
		fmt.Println(e.Name, len(b)) // 未压缩大小
	}
	zr, _ := zip.OpenReader(path)
	var helloBytes []byte
	for _, e := range zr.File {
		if e.Name == "hello.txt" {
			rc, _ := e.Open()
			helloBytes, _ = io.ReadAll(rc)
			rc.Close()
		}
	}
	zr.Close()
	fmt.Printf("hello: %s\n", string(bytes.TrimRight(helloBytes, "\n")))

	// 解压:逐条目建目录、拷字节(标准库没有 ExtractTo 一把梭)
	out := filepath.Join(os.TempDir(), fmt.Sprintf("a54-go-out-%d", os.Getpid()))
	os.MkdirAll(filepath.Join(out, "docs"), 0o755)
	r2, _ := zip.OpenReader(path)
	for _, e := range r2.File {
		rc, _ := e.Open()
		b, _ := io.ReadAll(rc)
		rc.Close()
		os.WriteFile(filepath.Join(out, e.Name), b, 0o644)
	}
	r2.Close()
	got, _ := os.ReadFile(filepath.Join(out, "hello.txt"))
	fmt.Println("extracted:", bytes.Equal(got, []byte("hello zip\n")))
	os.Remove(path)
	os.RemoveAll(out)
}
输出
entries: 2
hello.txt 10
docs/readme.md 23
hello: hello zip
extracted: true

Java v27.0.1

v27.0.1
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.zip.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // java.util.zip:创建 -> 列出 -> 读回(标准库)
        Path zipPath = Files.createTempFile("a54-java", ".zip");
        try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zipPath))) {
            zos.putNextEntry(new ZipEntry("hello.txt"));
            zos.write("hello zip\n".getBytes(StandardCharsets.UTF_8));
            zos.closeEntry();
            zos.putNextEntry(new ZipEntry("docs/readme.md")); // 条目名自带目录
            zos.write("# archive\nsecond entry\n".getBytes(StandardCharsets.UTF_8));
            zos.closeEntry();
        }
        try (ZipFile zf = new ZipFile(zipPath.toFile())) {
            System.out.println("entries: " + zf.size());
            Enumeration<? extends ZipEntry> en = zf.entries();
            while (en.hasMoreElements()) {
                ZipEntry e = en.nextElement();
                byte[] b = zf.getInputStream(e).readAllBytes();
                System.out.println(e.getName() + " " + b.length);
            }
            try (BufferedReader r = new BufferedReader(new InputStreamReader(
                    zf.getInputStream(zf.getEntry("hello.txt")), StandardCharsets.UTF_8))) {
                System.out.println("hello: " + r.readLine());
            }
        }
        // 解压:遍历条目逐个拷出
        Path out = Files.createTempDirectory("a54-java-out");
        try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zipPath))) {
            ZipEntry e;
            while ((e = zis.getNextEntry()) != null) {
                Path target = out.resolve(e.getName());
                if (e.isDirectory()) {
                    Files.createDirectories(target);
                } else {
                    Files.createDirectories(target.getParent());
                    Files.copy(zis, target, StandardCopyOption.REPLACE_EXISTING);
                }
            }
        }
        System.out.println("extracted: " + Files.readString(out.resolve("hello.txt")).equals("hello zip\n"));
        Files.deleteIfExists(zipPath);
    }
}
输出
entries: 2
hello.txt 10
docs/readme.md 23
hello: hello zip
extracted: true

JavaScript v26.13.1

v26.13.1
// Node 没有内置 zip(zlib 只有裸 DEFLATE),这里手写 stored(不压缩)模式
// ZIP:本地文件头 + 数据 + 中央目录 + EOCD 记录。python zipfile 能读回——
// 真互操作验证,见 notes。
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const u16 = (v) => { const b = Buffer.alloc(2); b.writeUInt16LE(v); return b; };
const u32 = (v) => { const b = Buffer.alloc(4); b.writeUInt32LE(v >>> 0); return b; };

// CRC-32(IEEE 802.3),查表实现
const CRC_TABLE = (() => {
  const t = new Uint32Array(256);
  for (let n = 0; n < 256; n++) {
    let c = n;
    for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
    t[n] = c >>> 0;
  }
  return t;
})();
const crc32 = (buf) => {
  let c = 0xffffffff;
  for (const byte of buf) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
  return (c ^ 0xffffffff) >>> 0;
};

function buildZip(files) {
  const parts = [], central = [];
  let offset = 0;
  for (const [name, data] of files) {
    const crc = crc32(data);
    const nameBuf = Buffer.from(name);
    const local = Buffer.concat([
      u32(0x04034b50), u16(20), u16(0), u16(0), // 本地头签名、版本、标志、stored(method 0)
      u16(0), u16(0), u32(crc),                 // 时间、日期、CRC32
      u32(data.length), u32(data.length),       // 压缩大小、大小
      u16(nameBuf.length), u16(0), nameBuf, data,
    ]);
    central.push(Buffer.concat([
      u32(0x02014b50), u16(20), u16(20), u16(0), u16(0), u16(0), u16(0),
      u32(crc), u32(data.length), u32(data.length),
      u16(nameBuf.length), u16(0), u16(0), u16(0), u16(0), u32(0), u32(offset), nameBuf,
    ]));
    parts.push(local);
    offset += local.length;
  }
  const cd = Buffer.concat(central);
  const eocd = Buffer.concat([
    u32(0x06054b50), u16(0), u16(0), u16(files.length), u16(files.length),
    u32(cd.length), u32(offset), u16(0),
  ]);
  return Buffer.concat([...parts, cd, eocd]);
}

const files = [['hello.txt', Buffer.from('hello zip\n')], ['docs/readme.md', Buffer.from('# archive\nsecond entry\n')]];
const zip = buildZip(files);
const zipPath = path.join(os.tmpdir(), `a54-js-${process.pid}.zip`);
fs.writeFileSync(zipPath, zip);
console.log('size:', zip.length);
console.log('entries:', files.length);
for (const [name, data] of files) console.log(name, data.length);
console.log('crc32(hello zip\\n):', crc32(files[0][1]).toString(16).padStart(8, '0'));
console.log('magic:', ...zip.subarray(0, 4));  // "PK\x03\x04"
fs.unlinkSync(zipPath);
输出
size: 253
entries: 2
hello.txt 10
docs/readme.md 23
crc32(hello zip\n): 4811c948
magic: 80 75 3 4

PHP v8.6.0

v8.6.0
// ZipArchive:创建 -> 列出 -> 解压。归档打包多文件并保留目录结构
//(gz/bz2 压缩单一流,见对应条目)
$path = tempnam(sys_get_temp_dir(), 'a54zip');
$zip = new ZipArchive();
$zip->open($path, ZipArchive::OVERWRITE);       // 覆盖模式打开(不存在则创建)
$zip->addFromString('hello.txt', "hello zip\n");          // 字符串直接入档
$zip->addFromString('docs/readme.md', "# archive\nsecond entry\n");  // 条目名带目录
$zip->close();                                   // 关闭才落盘(写中央目录)

$z = new ZipArchive();
$z->open($path);
echo "entries: ", $z->numFiles, PHP_EOL;
for ($i = 0; $i < $z->numFiles; $i++) {
    $s = $z->statIndex($i);                      // 条目元信息:名字/大小/CRC
    echo $s['name'], " ", $s['size'], PHP_EOL;   // size 是未压缩大小
}
echo "hello: ", trim($z->getFromName('hello.txt')), PHP_EOL;   // 按名读回内容
$out = sys_get_temp_dir() . '/a54zip-out-' . getmypid();       // 隔离目录防并发冲突
$z->extractTo($out);                             // 整档解压还原目录结构
echo "extracted: ", var_export(file_get_contents($out . '/hello.txt') === "hello zip\n", true), PHP_EOL;
$z->close();
unlink($path);
输出
entries: 2
hello.txt 10
docs/readme.md 23
hello: hello zip
extracted: true

Python v3.15.2

v3.15.2
import zipfile, tempfile, os

# zipfile:创建 -> 列出 -> 解压(标准库,无需安装)
path = tempfile.mktemp(suffix=".zip")
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
    z.writestr("hello.txt", "hello zip\n")                 # 字符串直接入档
    z.writestr("docs/readme.md", "# archive\nsecond entry\n")  # 条目名带目录

with zipfile.ZipFile(path) as z:
    print("entries:", len(z.infolist()))
    for i in z.infolist():
        print(i.filename, i.file_size)                     # file_size 是未压缩大小
    print("hello:", z.read("hello.txt").decode().strip())
    out = tempfile.mkdtemp()  # 隔离目录,并行跑也安全
    z.extractall(out)
print("extracted:", open(os.path.join(out, "hello.txt")).read() == "hello zip\n")
os.remove(path)
输出
entries: 2
hello.txt 10
docs/readme.md 23
hello: hello zip
extracted: True

Rust v1.99.1

v1.99.1
// zip crate:创建 -> 列出 -> 读回(依赖与本站其他条目共用同一 Cargo.toml 风格)
use std::io::{Read, Write};

fn main() {
    let path = std::env::temp_dir().join("a54-rs.zip");
    let f = std::fs::File::create(&path).unwrap();
    let mut w = zip::ZipWriter::new(f);
    w.start_file("hello.txt", zip::write::SimpleFileOptions::default()).unwrap();
    std::io::Write::write_all(&mut w, b"hello zip\n").unwrap();
    w.start_file("docs/readme.md", zip::write::SimpleFileOptions::default()).unwrap();
    std::io::Write::write_all(&mut w, b"# archive\nsecond entry\n").unwrap();
    drop(w); // 落盘中央目录

    let file = std::fs::File::open(&path).unwrap();
    let mut ar = zip::ZipArchive::new(file).unwrap();
    println!("entries: {}", ar.len());
    for i in 0..ar.len() {
        let mut e = ar.by_index(i).unwrap();
        println!("{} {}", e.name(), e.size()); // size = 未压缩大小
    }
    let mut s = String::new();
    ar.by_name("hello.txt").unwrap().read_to_string(&mut s).unwrap();
    println!("hello: {}", s.trim());

    // 解压:遍历逐条目拷出(crate 暴露的是逐条目 reader)
    let out = std::env::temp_dir().join("a54-rs-out");
    std::fs::create_dir_all(out.join("docs")).unwrap();
    for i in 0..ar.len() {
        let mut e = ar.by_index(i).unwrap();
        let mut bytes = Vec::new();
        e.read_to_end(&mut bytes).unwrap();
        std::fs::write(out.join(e.name().to_string()), bytes).unwrap();
    }
    let got = std::fs::read(out.join("hello.txt")).unwrap();
    println!("extracted: {}", got == b"hello zip\n");
    std::fs::remove_file(&path).unwrap();
    std::fs::remove_dir_all(out).unwrap();
}
输出
entries: 2
hello.txt 10
docs/readme.md 23
hello: hello zip
extracted: true

TypeScript v26.13.1

v26.13.1
// 与 JS 块同款的手写 stored 模式 ZIP,带类型。
interface ZipEntryInput {
  name: string;
  data: Buffer;
}

const u16 = (v: number): Buffer => { const b = Buffer.alloc(2); b.writeUInt16LE(v); return b; };
const u32 = (v: number): Buffer => { const b = Buffer.alloc(4); b.writeUInt32LE(v >>> 0); return b; };

const CRC_TABLE: Uint32Array = (() => {
  const t = new Uint32Array(256);
  for (let n = 0; n < 256; n++) {
    let c = n;
    for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
    t[n] = c >>> 0;
  }
  return t;
})();
const crc32 = (buf: Buffer): number => {
  let c = 0xffffffff;
  for (const byte of buf) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
  return (c ^ 0xffffffff) >>> 0;
};

function buildZip(files: ZipEntryInput[]): Buffer {
  const parts: Buffer[] = [], central: Buffer[] = [];
  let offset = 0;
  for (const { name, data } of files) {
    const crc = crc32(data);
    const nameBuf = Buffer.from(name);
    const local = Buffer.concat([
      u32(0x04034b50), u16(20), u16(0), u16(0), // 本地头签名、版本、标志、stored
      u16(0), u16(0), u32(crc),
      u32(data.length), u32(data.length),
      u16(nameBuf.length), u16(0), nameBuf, data,
    ]);
    central.push(Buffer.concat([
      u32(0x02014b50), u16(20), u16(20), u16(0), u16(0), u16(0), u16(0),
      u32(crc), u32(data.length), u32(data.length),
      u16(nameBuf.length), u16(0), u16(0), u16(0), u16(0), u32(0), u32(offset), nameBuf,
    ]));
    parts.push(local);
    offset += local.length;
  }
  const cd = Buffer.concat(central);
  const eocd = Buffer.concat([
    u32(0x06054b50), u16(0), u16(0), u16(files.length), u16(files.length),
    u32(cd.length), u32(offset), u16(0),
  ]);
  return Buffer.concat([...parts, cd, eocd]);
}

const files: ZipEntryInput[] = [
  { name: 'hello.txt', data: Buffer.from('hello zip\n') },
  { name: 'docs/readme.md', data: Buffer.from('# archive\nsecond entry\n') },
];
const zip = buildZip(files);
console.log('size:', zip.length);
console.log('entries:', files.length);
for (const f of files) console.log(f.name, f.data.length);
console.log('crc32(hello zip\\n):', crc32(files[0].data).toString(16).padStart(8, '0'));
console.log('magic:', ...zip.subarray(0, 4));
输出
size: 253
entries: 2
hello.txt 10
docs/readme.md 23
crc32(hello zip\n): 4811c948
magic: 80 75 3 4

语言差异说明

归档 vs 单文件压缩:gz/bz2(本站既有条目)压缩的是「一个流」,ZIP 是「多文件 + 目录结构的容器」——本地文件头 + 数据 + 中央目录 + EOCD 四段结构;stored(不压缩)模式结构最直白,deflate(方法 8)是通用压缩。

PHP:ZipArchive 是 zip 扩展(实测本机已加载;CI 需 php.ini 启用);addFromString 入档、statIndex 列元信息、getFromName 按名读回、extractTo 整档解压;close() 落盘中央目录。

C/C++:stdlib 无 zip——手写 stored 模式完整实现(本地头/CRC-32/中央目录/EOCD,~90 行),生成物可被任何 unzip 工具读回(教学价值:ZIP 就是字节序拼装);生产链 libzip(C)或 miniz(单文件 public domain)。

C#:System.IO.Compression 全内置(ZipArchive/ZipFile);ExtractToDirectory 一次调用还原目录树。

Go:archive/zip 标准库(zip.Writer 每条目一个 io.Writer);解压需手动逐条目(无 ExtractTo 一把梭)。

Java:java.util.zip 标准库(ZipOutputStream/ZipFile/ZipInputStream);条目名自带目录(docs/readme.md)。

JavaScript/TypeScript:Node 无内置 zip(zlib 只有裸 DEFLATE)——手写 stored 模式完整实现(CRC-32 查表 + 本地头 + 中央目录 + EOCD),产物被 python zipfile 读回验证(互操作实测通过);生产用 adm-zip/yauzl。

Python:zipfile 标准库满血(ZIP_DEFLATED 写压缩、infolist 列表、extractall 解压);本条 JS/C/C++ 手写产物均被 python zipfile testzip/读取验证。

Rust:zip crate(default-features = false + deflate,避免拉入全部压缩后端);逐条目 reader 风格。

TypeScript:同 JavaScript。