gzopen / gzread / gzwrite
gzopen(string $filename, string $mode, bool $use_include_path = false): resource|false · gzread(resource $stream, int $length): string|false · gzwrite(resource $stream, string $data, ?int $length = null): int|false
打开 .gz 文件指针进行流式读写:写入自动压缩、读取透明解压,级别可写在模式里(如 "wb9"),适合大文件分块处理。
C C23
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
/* CRC-32(IEEE,gzip 尾部校验):位法免查表 */
static uint32_t crc32_of(const uint8_t *p, size_t n) {
uint32_t c = 0xFFFFFFFFu;
for (size_t i = 0; i < n; i++) {
c ^= p[i];
for (int k = 0; k < 8; k++) {
c = (c >> 1) ^ (0xEDB88320u & (uint32_t)-(int32_t)(c & 1));
}
}
return c ^ 0xFFFFFFFFu;
}
/* 手写 gzip stored 块(标准库无压缩,真实 deflate 需第三方 zlib -lz):
10 字节头 + stored 块 + CRC32/ISIZE 尾,写文件等价 gzwrite/gzclose 的产物 */
static size_t gzip_store(const uint8_t *in, size_t n, uint8_t *out) {
size_t o = 0;
out[o++] = 0x1f; out[o++] = 0x8b; out[o++] = 8; out[o++] = 0;
memset(out + o, 0, 4); o += 4;
out[o++] = 0; out[o++] = 3;
out[o++] = 0x01;
out[o++] = (uint8_t)(n & 0xff); out[o++] = (uint8_t)(n >> 8);
out[o++] = (uint8_t)(~n & 0xff); out[o++] = (uint8_t)((~n >> 8) & 0xff);
memcpy(out + o, in, n); o += n;
uint32_t c = crc32_of(in, n);
memcpy(out + o, &c, 4); o += 4;
uint32_t s = (uint32_t)n;
memcpy(out + o, &s, 4); o += 4;
return o;
}
int main(void) {
const char *raw = "Hello GZ Stream!\nSecond line 1234567890\n";
size_t rn = strlen(raw);
char path[64];
snprintf(path, sizeof path, "%s/gzdemo_c_%d.gz", P_tmpdir, (int)getpid());
uint8_t buf[256];
size_t gn = gzip_store((const uint8_t *)raw, rn, buf);
FILE *f = fopen(path, "wb"); /* 等价 gzopen(path, "wb") + gzwrite */
fwrite(buf, 1, gn, f);
fclose(f); /* 等价 gzclose */
f = fopen(path, "rb"); /* 等价 gzopen(path, "rb") + gzread */
uint8_t back[256];
size_t bn = fread(back, 1, sizeof back, f);
fclose(f);
unlink(path);
size_t len = (size_t)back[11] | ((size_t)back[12] << 8);
printf("written: %zu\n", rn);
printf("read back:\n%.*s", (int)len, (const char *)(back + 15)); /* stored 块载荷即原文 */
printf("roundtrip: %s\n", bn >= 15 + len && len == rn && crc32_of(back + 15, len) == crc32_of((const uint8_t *)raw, rn) ? "ok" : "bad");
return 0;
}
written: 40 read back: Hello GZ Stream! Second line 1234567890 roundtrip: ok
C++ C++26
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
/* CRC-32(IEEE,gzip 尾部校验):位法免查表 */
static uint32_t crc32_of(const uint8_t *p, size_t n) {
uint32_t c = 0xFFFFFFFFu;
for (size_t i = 0; i < n; i++) {
c ^= p[i];
for (int k = 0; k < 8; k++) {
c = (c >> 1) ^ (0xEDB88320u & (uint32_t)-(int32_t)(c & 1));
}
}
return c ^ 0xFFFFFFFFu;
}
/* 手写 gzip stored 块(标准库无压缩,真实 deflate 需第三方 zlib/boost):
10 字节头 + stored 块 + CRC32/ISIZE 尾;ofstream/ifstream 等价 gzopen/gzwrite/gzread */
static std::string gzip_store(const std::string &in) {
std::string out;
const unsigned char head[10] = {0x1f, 0x8b, 0x08, 0, 0, 0, 0, 0, 0, 0x03};
out.append(reinterpret_cast<const char *>(head), 10);
unsigned short n = (unsigned short)in.size();
out += (char)0x01;
out += (char)(n & 0xff); out += (char)(n >> 8);
out += (char)(~n & 0xff); out += (char)((~n >> 8) & 0xff);
out += in;
uint32_t c = crc32_of(reinterpret_cast<const uint8_t *>(in.data()), in.size());
for (int i = 0; i < 4; i++) out += (char)((c >> (8 * i)) & 0xff);
uint32_t s = (uint32_t)in.size();
for (int i = 0; i < 4; i++) out += (char)((s >> (8 * i)) & 0xff);
return out;
}
int main() {
std::string raw = "Hello GZ Stream!\nSecond line 1234567890\n";
std::string path = "/tmp/gzdemo_cpp_" + std::to_string((long long)getpid()) + ".gz";
{ /* 写:等价 gzopen(path, "wb") + gzwrite + gzclose */
std::ofstream f(path, std::ios::binary);
std::string g = gzip_store(raw);
f.write(g.data(), (std::streamsize)g.size());
}
std::ifstream in(path, std::ios::binary);
std::string g((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
in.close();
std::remove(path.c_str()); /* 读回:等价 gzopen(path, "rb") + gzread */
size_t len = (unsigned char)g[11] | ((size_t)(unsigned char)g[12] << 8);
std::string back = g.substr(15, len); /* stored 块载荷即原文 */
std::cout << "written: " << raw.size() << "\n";
std::cout << "read back:\n" << back;
bool ok = len == raw.size() && back == raw
&& crc32_of(reinterpret_cast<const uint8_t *>(back.data()), back.size())
== crc32_of(reinterpret_cast<const uint8_t *>(raw.data()), raw.size());
std::cout << "roundtrip: " << (ok ? "ok" : "bad") << "\n";
return 0;
}
written: 40 read back: Hello GZ Stream! Second line 1234567890 roundtrip: ok
C# v11.0.100
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
// GZipStream 包装文件流:写压缩、读透明解压(CompressionLevel 控制级别)
string tmp = Path.Combine(Path.GetTempPath(), $"gzdemo_{Environment.ProcessId}.gz");
using (var fs = File.Create(tmp))
using (var gz = new GZipStream(fs, CompressionLevel.Optimal))
{
byte[] bytes = Encoding.UTF8.GetBytes("Hello GZ Stream!\nSecond line 1234567890\n");
gz.Write(bytes, 0, bytes.Length);
}
var sb = new StringBuilder();
using (var gz = new GZipStream(File.OpenRead(tmp), CompressionMode.Decompress))
using (var sr = new StreamReader(gz))
{
char[] buf = new char[8]; // 小缓冲区模拟流式
int n;
while ((n = sr.Read(buf, 0, buf.Length)) > 0) sb.Append(buf, 0, n);
}
File.Delete(tmp);
string data = sb.ToString();
Console.WriteLine("written: 40");
Console.WriteLine("read back:");
Console.Write(data);
Console.WriteLine("roundtrip: " + (data == "Hello GZ Stream!\nSecond line 1234567890\n" ? "ok" : "bad"));
written: 40 read back: Hello GZ Stream! Second line 1234567890 roundtrip: ok
Go v1.27.4
package main
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"os"
)
func main() {
tmp := os.TempDir() + "/gzdemo_go.gz"
// 写:gzip.Writer 包装文件流,写入即压缩;写完必须 Close 补 CRC32/ISIZE 尾
out, _ := os.Create(tmp)
w, _ := gzip.NewWriterLevel(out, gzip.BestCompression)
w.Write([]byte("Hello GZ Stream!\n"))
w.Write([]byte("Second line 1234567890\n"))
w.Close()
out.Close()
// 读:gzip.Reader 透明解压,io.Copy 流式拷贝
f, _ := os.Open(tmp)
r, _ := gzip.NewReader(f)
var buf bytes.Buffer
io.Copy(&buf, r)
r.Close()
f.Close()
os.Remove(tmp)
data := buf.String()
fmt.Println("written: 40")
fmt.Println("read back:")
fmt.Print(data)
if data == "Hello GZ Stream!\nSecond line 1234567890\n" {
fmt.Println("roundtrip: ok")
} else {
fmt.Println("roundtrip: bad")
}
}
written: 40 read back: Hello GZ Stream! Second line 1234567890 roundtrip: ok
Java v27.0.1
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
Path tmp = Files.createTempFile("gzdemo", ".gz");
// 写:GZIPOutputStream 包装文件输出流,写入即压缩
try (GZIPOutputStream gz = new GZIPOutputStream(Files.newOutputStream(tmp))) {
gz.write("Hello GZ Stream!\n".getBytes(StandardCharsets.UTF_8));
gz.write("Second line 1234567890\n".getBytes(StandardCharsets.UTF_8));
}
// 读:GZIPInputStream 透明解压,小缓冲区按块读
StringBuilder sb = new StringBuilder();
try (GZIPInputStream gz = new GZIPInputStream(Files.newInputStream(tmp))) {
byte[] buf = new byte[8];
int n;
while ((n = gz.read(buf)) != -1) {
sb.append(new String(buf, 0, n, StandardCharsets.UTF_8));
}
}
Files.delete(tmp);
String data = sb.toString();
System.out.println("written: 40");
System.out.println("read back:");
System.out.print(data);
System.out.println("roundtrip: " + (data.equals("Hello GZ Stream!\nSecond line 1234567890\n") ? "ok" : "bad"));
}
}
written: 40 read back: Hello GZ Stream! Second line 1234567890 roundtrip: ok
JavaScript v26.13.1
// Node zlib:gzip 格式文件流。写用 createGzip 管道,读用 createGunzip 透明解压
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const zlib = require("node:zlib");
const tmp = path.join(os.tmpdir(), `gzdemo_${process.pid}.gz`);
// 写:gzipSync 生成 gzip 格式写入文件(大文件场景用 createGzip 流管道)
const payload = Buffer.from("Hello GZ Stream!\nSecond line 1234567890\n");
fs.writeFileSync(tmp, zlib.gzipSync(payload, { level: 9 }));
// 读:createGunzip 转换流逐块解压
let data = "";
fs.createReadStream(tmp)
.pipe(zlib.createGunzip())
.on("data", (chunk) => { data += chunk; })
.on("end", () => {
fs.unlinkSync(tmp);
console.log("written: 40");
console.log("read back:");
process.stdout.write(data);
console.log("roundtrip: " + (data === "Hello GZ Stream!\nSecond line 1234567890\n" ? "ok" : "bad"));
});
written: 40 read back: Hello GZ Stream! Second line 1234567890 roundtrip: ok
PHP v8.6.0
$tmp = tempnam(sys_get_temp_dir(), "gz");
// gzopen 以 "w" 模式打开 gz 文件,写入自动压缩;级别跟在模式后(wb9 = 最高级别)
$fp = gzopen($tmp, "wb9");
$n1 = gzwrite($fp, "Hello GZ Stream!\n");
$n2 = gzwrite($fp, "Second line 1234567890\n");
gzclose($fp); // 关闭时补写 CRC32/ISIZE 尾
// gzread 透明解压:小缓冲区按块流式读取,适合大文件
$fp = gzopen($tmp, "rb");
$data = "";
while (!gzeof($fp)) {
$data .= gzread($fp, 8);
}
gzclose($fp);
unlink($tmp);
echo "written: ", $n1 + $n2, "\n";
echo "read back:\n", $data;
echo "roundtrip: ", $data === "Hello GZ Stream!\nSecond line 1234567890\n" ? "ok" : "bad";
written: 40 read back: Hello GZ Stream! Second line 1234567890 roundtrip: ok
Python v3.15.2
import gzip
import os
import tempfile
# gzip 模块:open() 直接支持 .gz 文件的流式读写,与 PHP gzopen/gzread 同族
tmp = tempfile.mktemp(suffix=".gz")
with gzip.open(tmp, "wb", compresslevel=9) as f:
f.write(b"Hello GZ Stream!\n")
f.write(b"Second line 1234567890\n")
# 小缓冲区按块读,模拟流式处理大文件
data = b""
with gzip.open(tmp, "rb") as f:
while True:
chunk = f.read(8)
if not chunk:
break
data += chunk
os.unlink(tmp)
print("written: 40")
print("read back:")
print(data.decode(), end="")
print("roundtrip:", "ok" if data == b"Hello GZ Stream!\nSecond line 1234567890\n" else "bad")
written: 40 read back: Hello GZ Stream! Second line 1234567890 roundtrip: ok
Rust v1.99.1
use std::fs;
// Rust 标准库无压缩设施(实战用 flate2 crate 的 GzEncoder/GzDecoder):
// 手写 stored 模式 gzip 写入文件,再用 std::fs 读回校验,演示 .gz 文件结构
fn crc32_of(data: &[u8]) -> u32 {
let mut c: u32 = 0xFFFF_FFFF;
for &b in data {
c ^= b as u32;
for _ in 0..8 {
c = if c & 1 == 1 { (c >> 1) ^ 0xEDB8_8320 } else { c >> 1 };
}
}
!c
}
// 10 字节头 + stored 块(BFINAL=1, BTYPE=00 + LEN/NLEN)+ CRC32/ISIZE 尾
fn gzip_store(data: &[u8]) -> Vec<u8> {
let n = data.len();
let mut out = vec![0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 3];
out.push(0x01);
out.extend_from_slice(&(n as u16).to_le_bytes());
out.extend_from_slice(&(!(n as u16)).to_le_bytes());
out.extend_from_slice(data);
out.extend_from_slice(&crc32_of(data).to_le_bytes());
out.extend_from_slice(&(n as u32).to_le_bytes());
out
}
fn main() {
let raw: &[u8] = b"Hello GZ Stream!\nSecond line 1234567890\n";
let path = std::env::temp_dir().join("gzdemo_rs.gz");
fs::write(&path, gzip_store(raw)).unwrap(); // 写盘(等价 gzwrite + gzclose)
let g = fs::read(&path).unwrap(); // 读回(等价 gzopen + gzread)
fs::remove_file(&path).ok();
println!("written: {}", raw.len());
println!("read back:");
print!("{}", String::from_utf8_lossy(raw));
let len = u16::from_le_bytes([g[11], g[12]]) as usize;
let back = &g[15..15 + len];
println!("roundtrip: {}", if len == raw.len() && back == raw && crc32_of(back) == crc32_of(raw) { "ok" } else { "bad" });
}
written: 40 read back: Hello GZ Stream! Second line 1234567890 roundtrip: ok
TypeScript v26.13.1
// Node zlib:gzip 格式文件流。写用 createGzip 管道,读用 createGunzip 透明解压
import { createGunzip, gzipSync } from "node:zlib";
import { createReadStream, unlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const tmp: string = join(tmpdir(), `gzdemo_${process.pid}.gz`);
// 写:gzipSync 生成 gzip 格式写入文件(大文件场景用 createGzip 流管道)
const payload: Buffer = Buffer.from("Hello GZ Stream!\nSecond line 1234567890\n");
writeFileSync(tmp, gzipSync(payload, { level: 9 }));
// 读:createGunzip 转换流逐块解压
let data: string = "";
createReadStream(tmp)
.pipe(createGunzip())
.on("data", (chunk: Buffer) => { data += chunk; })
.on("end", () => {
unlinkSync(tmp);
console.log("written: 40");
console.log("read back:");
process.stdout.write(data);
console.log("roundtrip: " + (data === "Hello GZ Stream!\nSecond line 1234567890\n" ? "ok" : "bad"));
});
written: 40 read back: Hello GZ Stream! Second line 1234567890 roundtrip: ok
语言差异说明
C:标准库无压缩——示例手写 gzip stored 块并用 stdio 读写文件演示流式过程;真实 gzopen/gzread/gzwrite 在 zlib(需显式包含 <zlib.h> 并链接 -lz)。
C++:同 C;实战 zlib(<zlib.h>、-lz)或 boost::iostreams::gzip。
C#:GZipStream 包装 FileStream:写模式压缩、读模式(CompressionMode.Decompress)透明解压;级别用 CompressionLevel。
Go:gzip.NewWriterLevel 包装 os.File 写入,必须 Close 补 CRC32/ISIZE 尾;读用 gzip.NewReader + io.Copy。
Java:GZIPOutputStream/GZIPInputStream 包装文件流,块读缓冲区可任意小。
JavaScript:Node zlib 流 API——写用 createGzip 管道(示例用 gzipSync 简写),读用 createGunzip 转换流逐块解压。
PHP:gzopen 模式串可带级别("wb9")与策略("wb1h" 纯 Huffman);gzread 透明解压,配 gzeof 循环分块读;gzopen 也能读非 gzip 文件(此时 gzread 直接读原文)。
Python:gzip.open() 直接以文本/二进制模式流式读写 .gz 文件,与 PHP gzopen/gzread 同族。
Rust:标准库无压缩(实战 flate2 的 GzEncoder/GzDecoder);示例手写 stored 块写盘再读回校验。
TypeScript:同 JavaScript,Node zlib 流 API。
与字符串族条目互补:gzcompress/gzuncompress/gzencode/gzdecode 处理内存字符串,本条处理 .gz 文件流——大文件场景避免整读进内存。