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
Opens a .gz file pointer for streaming I/O: writes are compressed and reads transparently decompressed; the level can be embedded in the mode (e.g. "wb9") — suited for chunked processing of large files.
C C23
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
/* CRC-32 (IEEE, the gzip trailer checksum): bitwise method, no lookup table */
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;
}
/* Hand-written gzip stored block (the C standard library has no compression; real deflate
needs third-party zlib with -lz): 10-byte header + stored block + CRC32/ISIZE trailer,
streamed to a file like gzwrite/gzclose would produce */
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-block payload == the original bytes */
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, the gzip trailer checksum): bitwise method, no lookup table */
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;
}
/* Hand-written gzip stored block (the C++ standard library has no compression either; real
deflate needs third-party zlib/boost): 10-byte header + stored block + CRC32/ISIZE trailer;
ofstream/ifstream play the roles of 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";
{ /* write: == 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(); /* read back: == gzopen(path, "rb") + gzread */
std::remove(path.c_str());
size_t len = (unsigned char)g[11] | ((size_t)(unsigned char)g[12] << 8);
std::string back = g.substr(15, len); /* stored-block payload == the original bytes */
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.IO.Compression;
using System.Text;
// GZipStream wraps a file stream: Compress on write, transparent Decompress on read (CompressionLevel picks the level)
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]; // small buffer to simulate streaming
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"
// write: gzip.Writer wraps the file stream (compressed on the fly); Close flushes the CRC32/ISIZE trailer
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()
// read: gzip.Reader decompresses transparently; io.Copy streams it out
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");
// write: GZIPOutputStream wraps the file output stream (compressed on the fly)
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));
}
// read: GZIPInputStream decompresses transparently; small buffer reads chunk by chunk
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: streaming gzip files — createGzip pipe to write, createGunzip to decode transparently
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`);
// write: gzipSync produces the gzip format on disk (large files would use a createGzip pipe)
const payload = Buffer.from("Hello GZ Stream!\nSecond line 1234567890\n");
fs.writeFileSync(tmp, zlib.gzipSync(payload, { level: 9 }));
// read: createGunzip transform stream decompresses chunk by chunk
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 with mode "w" opens a gz file for writing (compressed on the fly);
// the compression level goes right in the mode string ("wb9" = best)
$fp = gzopen($tmp, "wb9");
$n1 = gzwrite($fp, "Hello GZ Stream!\n");
$n2 = gzwrite($fp, "Second line 1234567890\n");
gzclose($fp); // closing appends the CRC32/ISIZE trailer
// gzread decompresses transparently: read in small chunks to stream large files
$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
# The gzip module streams .gz files directly via open() — the same family as 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")
# read in small chunks to simulate streaming a large file
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's standard library has no compression (flate2's GzEncoder/GzDecoder in real projects):
// hand-write a stored-mode gzip file, read it back with std::fs, and validate the .gz structure
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-byte header + stored block (BFINAL=1, BTYPE=00 + LEN/NLEN) + CRC32/ISIZE trailer
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(); // write to disk (== gzwrite + gzclose)
let g = fs::read(&path).unwrap(); // read back (== 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: streaming gzip files — createGzip pipe to write, createGunzip to decode transparently
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`);
// write: gzipSync produces the gzip format on disk (large files would use a createGzip pipe)
const payload: Buffer = Buffer.from("Hello GZ Stream!\nSecond line 1234567890\n");
writeFileSync(tmp, gzipSync(payload, { level: 9 }));
// read: createGunzip transform stream decompresses chunk by chunk
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
Language differences
C: no compression in the standard library — the example hand-writes a gzip stored block and streams it through stdio; the real gzopen/gzread/gzwrite live in zlib (explicitly include <zlib.h> and link -lz).
C++: same as C; real work uses zlib (<zlib.h>, -lz) or boost::iostreams::gzip.
C#: GZipStream wraps a FileStream — Compress mode on write, CompressionMode.Decompress transparently decodes on read; level via CompressionLevel.
Go: gzip.NewWriterLevel wrapping os.File for writing (must Close to append the CRC32/ISIZE trailer); gzip.NewReader + io.Copy to read.
Java: GZIPOutputStream/GZIPInputStream wrap file streams; the read buffer can be arbitrarily small.
JavaScript: Node zlib streaming — createGzip pipe to write (gzipSync shorthand in the example), createGunzip transform stream for chunked reads.
PHP: the gzopen mode string accepts a level ("wb9") and strategy ("wb1h" Huffman-only); gzread decompresses transparently, loop it with gzeof for chunked reads; gzopen can even open non-gzip files (gzread then reads raw bytes).
Python: gzip.open() streams .gz files directly in text or binary mode — the same family as PHP gzopen/gzread.
Rust: nothing in std (flate2's GzEncoder/GzDecoder in real projects); the example hand-writes a stored block to disk and validates it back.
TypeScript: same as JavaScript — the Node zlib streaming API.
Complements the string-family entries: gzcompress/gzuncompress/gzencode/gzdecode handle in-memory strings, while this one streams .gz files — large files never load fully into memory.