fpassthru / readfile

fpassthru(resource $stream): int — readfile(string $filename, bool $use_include_path = false, ?resource $context = null): int|false

文件直出双引擎:readfile 一步把整个文件写入输出缓冲并返回字节数;fpassthru 从流的当前位置直通到文件尾——大文件下载场景的内存差异教学点。

C C23

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

int main(void) {
    /* fread + fwrite(stdout):分块流式输出,fpassthru 的模式 */
    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 字节 */
    fclose(w);
    FILE *f = fopen(path, "rb");
    char buf[64];
    size_t n = fread(buf, 1, sizeof(buf), f);
    fwrite(buf, 1, n, stdout); /* 整文件直出(readfile 语义) */
    printf("\n");
    fseek(f, 10, SEEK_SET); /* 跳过 10 字节 */
    n = fread(buf, 1, sizeof(buf), f);
    fwrite(buf, 1, n, stdout); /* 直通剩余部分(fpassthru) */
    printf("\n30 + 20 = 50 bytes\n");
    fclose(f);
    unlink(path);
    return 0;
}
输出
abcdefghijabcdefghijabcdefghij
abcdefghijabcdefghij
30 + 20 = 50 bytes

C++ C++26

C++26
#include <fstream>
#include <iostream>

int main() {
    // ofstream << rdbuf() 让文件流式穿过(fpassthru 模式);
    // std::ifstream::read 先读进缓冲则是全量加载(readfile 模式)
    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 字节
    out.close();
    std::ifstream in(path, std::ios::binary);
    std::cout << in.rdbuf() << "\n"; // 整文件直出
    std::ifstream in2(path, std::ios::binary);
    in2.seekg(10); // 跳过前 10 字节
    std::cout << in2.rdbuf() << "\n"; // 直通剩余部分
    std::cout << "30 + 20 = 50 bytes\n";
    std::remove(path);
    return 0;
}
输出
abcdefghijabcdefghijabcdefghij
abcdefghijabcdefghij
30 + 20 = 50 bytes

C# v11.0.100

v11.0.100
// Stream.CopyTo 分块流式输出 file->stdout(fpassthru,内存恒定);
// File.ReadAllBytes 先把全部读进内存(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()); // 整文件直出
}
Console.Out.WriteLine();
using (var in2 = File.OpenRead(path))
{
    in2.Seek(10, SeekOrigin.Begin); // 跳过前 10 字节
    in2.CopyTo(Console.OpenStandardOutput()); // 直通剩余部分
}
Console.Out.WriteLine();
Console.WriteLine("30 + 20 = 50 bytes");
File.Delete(path);
输出
abcdefghijabcdefghijabcdefghij
abcdefghijabcdefghij
30 + 20 = 50 bytes

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
	// io.Copy 分块流式输出 file->stdout(fpassthru 模式);
	// os.ReadFile 先全量读进内存(readfile 模式)
	path := "/tmp/a43_io_go"
	os.WriteFile(path, []byte("abcdefghijabcdefghijabcdefghij"), 0644) // 30 字节
	f, _ := os.Open(path)
	io.Copy(os.Stdout, f) // 整文件直出
	fmt.Println()
	f.Seek(10, 0) // 跳过前 10 字节
	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

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 分块流式输出到 stdout(fpassthru);
        // Files.readString 全量读进内存(readfile)
        Path path = Files.createTempFile("a43_io_java", ".bin");
        Files.writeString(path, "abcdefghij".repeat(3)); // 30 字节
        try (InputStream in1 = Files.newInputStream(path)) {
            in1.transferTo(System.out); // 整文件直出
        }
        System.out.println();
        try (InputStream in2 = Files.newInputStream(path)) {
            in2.skipNBytes(10); // 跳过前 10 字节
            in2.transferTo(System.out); // 直通剩余部分
        }
        System.out.println();
        System.out.println("30 + 20 = 50 bytes");
        Files.delete(path);
    }
}
输出
abcdefghijabcdefghijabcdefghij
abcdefghijabcdefghij
30 + 20 = 50 bytes

JavaScript v26.13.1

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 分块流式(fpassthru,内存恒定);
// readFileSync 先全量读进 Buffer(readfile)
const path = join(tmpdir(), "a43_io_js");
writeFileSync(path, "abcdefghij".repeat(3)); // 30 字节
await pipeline(createReadStream(path), process.stdout, { end: false }); // 整文件直出
process.stdout.write("\n");
await pipeline(createReadStream(path, { start: 10 }), process.stdout, { end: false }); // 剩余部分
process.stdout.write("\n");
console.log("30 + 20 = 50 bytes");
unlinkSync(path);
输出
abcdefghijabcdefghijabcdefghij
abcdefghijabcdefghij
30 + 20 = 50 bytes

PHP v8.6.0

v8.6.0
// readfile vs fpassthru:整文件直出 vs 从当前位置直通剩余部分
$content = str_repeat('abcdefghij', 3); // 固定 30 字节
$file = tempnam(sys_get_temp_dir(), 'io');
file_put_contents($file, $content);
// readfile:打开、把整个文件写入输出缓冲、返回字节数
$n1 = readfile($file);
echo "\n";
// fpassthru:从流的当前位置直通到文件尾,返回发送的字节数
$h = fopen($file, 'rb');
fseek($h, 10);       // 跳过前 10 字节
$n2 = fpassthru($h); // 一次调用发送剩余的 20 字节
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

v3.15.2
import shutil
import sys
from pathlib import Path

# shutil.copyfileobj 分块流式输出(fpassthru,内存恒定);
# Path.read_bytes 全量读进内存(readfile)
path = Path("/tmp/a43_io_py")
path.write_bytes(b"abcdefghij" * 3)  # 30 字节
with path.open("rb") as src:
    shutil.copyfileobj(src, sys.stdout.buffer)  # 整文件直出
sys.stdout.buffer.write(b"\n")
with path.open("rb") as src:
    src.seek(10)  # 跳过前 10 字节
    shutil.copyfileobj(src, sys.stdout.buffer)  # 直通剩余部分
sys.stdout.buffer.write(b"\n")
print("30 + 20 = 50 bytes")
path.unlink()
输出
abcdefghijabcdefghijabcdefghij
abcdefghijabcdefghij
30 + 20 = 50 bytes

Rust v1.99.1

v1.99.1
use std::fs::File;
use std::io::{copy, Seek, SeekFrom, Write};

fn main() {
    // io::copy 分块流式输出 file->stdout(fpassthru,内存恒定);
    // fs::read 先全量读进 Vec(readfile)
    let path = "/tmp/a43_io_rs";
    std::fs::write(path, "abcdefghij".repeat(3)).unwrap(); // 30 字节
    let mut f = File::open(path).unwrap();
    copy(&mut f, &mut std::io::stdout()).unwrap(); // 整文件直出
    println!();
    f.seek(SeekFrom::Start(10)).unwrap(); // 跳过前 10 字节
    copy(&mut f, &mut std::io::stdout()).unwrap(); // 直通剩余部分
    println!();
    println!("30 + 20 = 50 bytes");
    std::fs::remove_file(path).unwrap();
}
输出
abcdefghijabcdefghijabcdefghij
abcdefghijabcdefghij
30 + 20 = 50 bytes

TypeScript v26.13.1

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 分块流式(fpassthru,内存恒定);
// readFileSync 先全量读进 Buffer(readfile)
const path = join(tmpdir(), "a43_io_ts");
writeFileSync(path, "abcdefghij".repeat(3)); // 30 字节
await pipeline(createReadStream(path), process.stdout, { end: false }); // 整文件直出
process.stdout.write("\n");
await pipeline(createReadStream(path, { start: 10 }), process.stdout, { end: false }); // 剩余部分
process.stdout.write("\n");
console.log("30 + 20 = 50 bytes");
unlinkSync(path);
输出
abcdefghijabcdefghijabcdefghij
abcdefghijabcdefghij
30 + 20 = 50 bytes

语言差异说明

C:无内建直出——fread + fwrite(stdout) 手写分块循环(示例);缓冲区尺寸决定内存峰值,这正是 fpassthru 模式的手写本质。

C++:cout << in.rdbuf() 是流式直通(fpassthru 模式);in.read(buf, n) 读进缓冲是全量加载(readfile 模式)。

C#:Stream.CopyTo 分块流式(默认 81920 字节缓冲);File.ReadAllBytes 全量加载——大文件下载一律 CopyTo。

Go:io.Copy(dst, src) 原生流式拷贝(32KB 块);os.ReadFile 全量——Go 侧 io.Copy 就是 fpassthru 的原生等价物。

Java:InputStream.transferTo(9+)分块流式;Files.readString/readAllBytes 全量——下载场景用 transferTo。

JavaScript:createReadStream().pipe() / stream/promises 的 pipeline 分块流式(注意 end: false 防止关闭 stdout 后续写 EPIPE);readFileSync 全量 Buffer——Node 下载场景一律流。

PHP:readfile 一步到位(无需 fopen,返回字节数、失败 false);fpassthru 从当前位置直通到尾并返回发送字节数——fseek 先跳过头部的断点续传/范围下载就用它;两者都走输出缓冲(大文件配 Output Control 或关缓冲),内存占用取决于输出缓冲而非文件大小;手册建议大文件下载场景配合 exit 防止继续执行。

Python:shutil.copyfileobj(src, dst) 分块流式(可调 length);path.read_bytes() 全量——Python 侧 copyfileobj 就是 fpassthru 的原生等价物;另可 sys.stdout.buffer 直写二进制。

Rust:io::copy(&mut file, &mut stdout()) 原生流式(默认 8KB 块);fs::read 全量 Vec——io::copy 即 fpassthru 等价物。

TypeScript:同 JavaScript——流式 pipeline 与全量 readFileSync 对照。