fpassthru / readfile
fpassthru(resource $stream): int — readfile(string $filename, bool $use_include_path = false, ?resource $context = null): int|false
Two engines for dumping files: readfile writes the whole file to the output buffer in one step and returns the byte count; fpassthru streams from the stream's current position to EOF - the memory-difference teaching point for large downloads.
C C23
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(void) {
/* fread + fwrite(stdout): block streaming, the fpassthru pattern */
const char *path = "/tmp/a43_io_c";
FILE *w = fopen(path, "wb");
for (int i = 0; i < 3; i++) fwrite("abcdefghij", 1, 10, w); /* 30 bytes */
fclose(w);
FILE *f = fopen(path, "rb");
char buf[64];
size_t n = fread(buf, 1, sizeof(buf), f);
fwrite(buf, 1, n, stdout); /* whole-file dump (readfile semantics) */
printf("\n");
fseek(f, 10, SEEK_SET); /* skip 10 bytes */
n = fread(buf, 1, sizeof(buf), f);
fwrite(buf, 1, n, stdout); /* stream the remainder (fpassthru) */
printf("\n30 + 20 = 50 bytes\n");
fclose(f);
unlink(path);
return 0;
}
abcdefghijabcdefghijabcdefghij abcdefghijabcdefghij 30 + 20 = 50 bytes
C++ C++26
#include <fstream>
#include <iostream>
int main() {
// ofstream << rdbuf() streams the file through (fpassthru pattern);
// std::ifstream::read into a buffer loads it all first (readfile pattern)
const char *path = "/tmp/a43_io_cpp";
std::ofstream out(path, std::ios::binary);
for (int i = 0; i < 3; i++) out.write("abcdefghij", 10); // 30 bytes
out.close();
std::ifstream in(path, std::ios::binary);
std::cout << in.rdbuf() << "\n"; // whole-file dump
std::ifstream in2(path, std::ios::binary);
in2.seekg(10); // skip the first 10 bytes
std::cout << in2.rdbuf() << "\n"; // stream the remainder
std::cout << "30 + 20 = 50 bytes\n";
std::remove(path);
return 0;
}
abcdefghijabcdefghijabcdefghij abcdefghijabcdefghij 30 + 20 = 50 bytes
C# v11.0.100
// Stream.CopyTo streams file->stdout in blocks (fpassthru, constant memory);
// File.ReadAllBytes loads everything into memory first (readfile)
var path = Path.Combine(Path.GetTempPath(), "a43_io_cs");
File.WriteAllBytes(path, System.Text.Encoding.ASCII.GetBytes(string.Concat(System.Linq.Enumerable.Repeat("abcdefghij", 3))));
using (var in1 = File.OpenRead(path))
{
in1.CopyTo(Console.OpenStandardOutput()); // whole-file dump
}
Console.Out.WriteLine();
using (var in2 = File.OpenRead(path))
{
in2.Seek(10, SeekOrigin.Begin); // skip the first 10 bytes
in2.CopyTo(Console.OpenStandardOutput()); // stream the remainder
}
Console.Out.WriteLine();
Console.WriteLine("30 + 20 = 50 bytes");
File.Delete(path);
abcdefghijabcdefghijabcdefghij abcdefghijabcdefghij 30 + 20 = 50 bytes
Go v1.27.4
package main
import (
"fmt"
"io"
"os"
)
func main() {
// io.Copy streams file->stdout in blocks (the fpassthru pattern);
// os.ReadFile loads everything into memory first (the readfile pattern)
path := "/tmp/a43_io_go"
os.WriteFile(path, []byte("abcdefghijabcdefghijabcdefghij"), 0644) // 30 bytes
f, _ := os.Open(path)
io.Copy(os.Stdout, f) // whole-file dump
fmt.Println()
f.Seek(10, 0) // skip the first 10 bytes
io.Copy(os.Stdout, f)
fmt.Println()
fmt.Println("30 + 20 = 50 bytes")
f.Close()
os.Remove(path)
}
abcdefghijabcdefghijabcdefghij abcdefghijabcdefghij 30 + 20 = 50 bytes
Java v27.0.1
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
// InputStream.transferTo streams to stdout in blocks (fpassthru);
// Files.readString loads everything into memory (readfile)
Path path = Files.createTempFile("a43_io_java", ".bin");
Files.writeString(path, "abcdefghij".repeat(3)); // 30 bytes
try (InputStream in1 = Files.newInputStream(path)) {
in1.transferTo(System.out); // whole-file dump
}
System.out.println();
try (InputStream in2 = Files.newInputStream(path)) {
in2.skipNBytes(10); // skip the first 10 bytes
in2.transferTo(System.out); // stream the remainder
}
System.out.println();
System.out.println("30 + 20 = 50 bytes");
Files.delete(path);
}
}
abcdefghijabcdefghijabcdefghij abcdefghijabcdefghij 30 + 20 = 50 bytes
JavaScript v26.13.1
import { createReadStream, writeFileSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pipeline } from "node:stream/promises";
// createReadStream + pipeline streams in chunks (fpassthru, constant memory);
// readFileSync loads everything into a Buffer first (readfile)
const path = join(tmpdir(), "a43_io_js");
writeFileSync(path, "abcdefghij".repeat(3)); // 30 bytes
await pipeline(createReadStream(path), process.stdout, { end: false }); // whole-file dump
process.stdout.write("\n");
await pipeline(createReadStream(path, { start: 10 }), process.stdout, { end: false }); // remainder
process.stdout.write("\n");
console.log("30 + 20 = 50 bytes");
unlinkSync(path);
abcdefghijabcdefghijabcdefghij abcdefghijabcdefghij 30 + 20 = 50 bytes
PHP v8.6.0
// readfile vs fpassthru: whole-file dump vs stream-the-remainder passthrough
$content = str_repeat('abcdefghij', 3); // 30 fixed bytes
$file = tempnam(sys_get_temp_dir(), 'io');
file_put_contents($file, $content);
// readfile: opens, dumps the WHOLE file to the output buffer, returns bytes
$n1 = readfile($file);
echo "\n";
// fpassthru: dumps from the CURRENT position to EOF, returns bytes sent
$h = fopen($file, 'rb');
fseek($h, 10); // skip the first 10 bytes
$n2 = fpassthru($h); // sends the remaining 20 in one call
echo "\n";
fclose($h);
printf("readfile %d + fpassthru %d = %d bytes\n", $n1, $n2, $n1 + $n2);
unlink($file);
abcdefghijabcdefghijabcdefghij abcdefghijabcdefghij readfile 30 + fpassthru 20 = 50 bytes
Python v3.15.2
import shutil
import sys
from pathlib import Path
# shutil.copyfileobj streams in blocks (fpassthru, constant memory);
# Path.read_bytes loads everything into memory (readfile)
path = Path("/tmp/a43_io_py")
path.write_bytes(b"abcdefghij" * 3) # 30 bytes
with path.open("rb") as src:
shutil.copyfileobj(src, sys.stdout.buffer) # whole-file dump
sys.stdout.buffer.write(b"\n")
with path.open("rb") as src:
src.seek(10) # skip the first 10 bytes
shutil.copyfileobj(src, sys.stdout.buffer) # stream the remainder
sys.stdout.buffer.write(b"\n")
print("30 + 20 = 50 bytes")
path.unlink()
abcdefghijabcdefghijabcdefghij abcdefghijabcdefghij 30 + 20 = 50 bytes
Rust v1.99.1
use std::fs::File;
use std::io::{copy, Seek, SeekFrom, Write};
fn main() {
// io::copy streams file->stdout in blocks (fpassthru, constant memory);
// fs::read loads everything into a Vec first (readfile)
let path = "/tmp/a43_io_rs";
std::fs::write(path, "abcdefghij".repeat(3)).unwrap(); // 30 bytes
let mut f = File::open(path).unwrap();
copy(&mut f, &mut std::io::stdout()).unwrap(); // whole-file dump
println!();
f.seek(SeekFrom::Start(10)).unwrap(); // skip the first 10 bytes
copy(&mut f, &mut std::io::stdout()).unwrap(); // stream the remainder
println!();
println!("30 + 20 = 50 bytes");
std::fs::remove_file(path).unwrap();
}
abcdefghijabcdefghijabcdefghij abcdefghijabcdefghij 30 + 20 = 50 bytes
TypeScript v26.13.1
import { createReadStream, writeFileSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pipeline } from "node:stream/promises";
// createReadStream + pipeline streams in chunks (fpassthru, constant memory);
// readFileSync loads everything into a Buffer first (readfile)
const path = join(tmpdir(), "a43_io_ts");
writeFileSync(path, "abcdefghij".repeat(3)); // 30 bytes
await pipeline(createReadStream(path), process.stdout, { end: false }); // whole-file dump
process.stdout.write("\n");
await pipeline(createReadStream(path, { start: 10 }), process.stdout, { end: false }); // remainder
process.stdout.write("\n");
console.log("30 + 20 = 50 bytes");
unlinkSync(path);
abcdefghijabcdefghijabcdefghij abcdefghijabcdefghij 30 + 20 = 50 bytes
Language differences
C: no built-in dump - fread + fwrite(stdout) in a hand-written block loop (example); the buffer size sets the memory peak, which is exactly the hand-written essence of the fpassthru pattern.
C++: cout << in.rdbuf() is streaming passthrough (the fpassthru pattern); in.read(buf, n) into a buffer is whole-file loading (the readfile pattern).
C#: Stream.CopyTo streams in blocks (81920-byte default buffer); File.ReadAllBytes loads it all - use CopyTo for large downloads.
Go: io.Copy(dst, src) is native block-streaming (32KB blocks); os.ReadFile loads it all - Go's io.Copy is the native fpassthru equivalent.
Java: InputStream.transferTo (9+) streams in blocks; Files.readString/readAllBytes load it all - use transferTo for downloads.
JavaScript: createReadStream().pipe() / pipeline from stream/promises streams in chunks (note end: false to avoid EPIPE writing after stdout closes); readFileSync loads it all as a Buffer - Node downloads are always streamed.
PHP: readfile does it in one call (no fopen needed, returns the byte count or false); fpassthru streams from the CURRENT position to EOF and returns the bytes sent - fseek past a header first and it serves range/resume downloads; both write through the output buffer (for large files pair with Output Control or disable buffering), so memory depends on the buffer, not the file size; the manual suggests pairing large downloads with exit to stop further execution.
Python: shutil.copyfileobj(src, dst) streams in blocks (tunable length); path.read_bytes() loads it all - Python's copyfileobj is the native fpassthru equivalent; sys.stdout.buffer writes binary directly.
Rust: io::copy(&mut file, &mut stdout()) is native streaming (8KB default blocks); fs::read loads a full Vec - io::copy is the fpassthru equivalent.
TypeScript: same as JavaScript - streamed pipeline vs full readFileSync.