stream_copy_to_stream

stream_copy_to_stream(resource $from, resource $to, ?int $length = null, int $offset = 0, ?resource $context = null): int|false

流对流拷贝:从 $from 当前位置(或 offset>0 时先寻址)拷到 EOF,length 限字节数;返回实际拷贝字节数——大文件零手动缓冲(内部按块循环),是 Go io.Copy 的原生对应。

C C23

C23
#include <stdio.h>

int main(void) {
    FILE *src = tmpfile();
    fputs("abcdefghij", src);
    rewind(src);
    FILE *dst = tmpfile();

    /* C 标准库没有流对流拷贝:带计数的 fread/fwrite 循环
     * 就是可移植的等价实现。 */
    char buf[64];
    size_t n, total = 0;
    while ((n = fread(buf, 1, sizeof buf, src)) > 0) {
        fwrite(buf, 1, n, dst);
        total += n;
    }
    rewind(dst);
    printf("copied: %zu\n", total);
    int c;
    while ((c = fgetc(dst)) != EOF) {
        putchar(c);
    }
    printf("\n");
    return 0;
}
输出
copied: 10
abcdefghij

C++ C++26

C++26
#include <cstdio>

int main() {
    FILE *src = tmpfile();
    fputs("abcdefghij", src);
    rewind(src);
    FILE *dst = tmpfile();

    // stdio 无拷贝助手;显式计数循环是可移植核心
    //(iostream 风格会用 rdbuf 或 streambuf 迭代器)。
    char buf[64];
    std::size_t n, total = 0;
    while ((n = fread(buf, 1, sizeof buf, src)) > 0) {
        fwrite(buf, 1, n, dst);
        total += n;
    }
    rewind(dst);
    std::printf("copied: %zu\n", total);
    int c;
    while ((c = fgetc(dst)) != EOF) {
        std::putchar(c);
    }
    std::printf("\n");
    return 0;
}
输出
copied: 10
abcdefghij

C# v11.0.100

v11.0.100
using System.Text;

byte[] data = Encoding.ASCII.GetBytes("abcdefghij");
using var src = new MemoryStream(data);
using var dst = new MemoryStream();

// Stream.CopyTo 是直接对应物:零手动缓冲。
src.CopyTo(dst);
Console.WriteLine($"copied: {dst.Length}");
Console.WriteLine(Encoding.ASCII.GetString(dst.ToArray()));
输出
copied: 10
abcdefghij

Go v1.27.4

v1.27.4
package main

import (
	"bytes"
	"fmt"
	"io"
)

func main() {
	src := bytes.NewBufferString("abcdefghij")
	var dst bytes.Buffer

	// io.Copy 是 stream_copy_to_stream 的原生对应;
	// 可能时还会走 sendfile 等零拷贝捷径。
	n, err := io.Copy(&dst, src)
	if err != nil {
		panic(err)
	}
	fmt.Println("copied:", n)
	fmt.Println(dst.String())
}
输出
copied: 10
abcdefghij

Java v27.0.1

v27.0.1
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) throws Exception {
        InputStream src = new ByteArrayInputStream("abcdefghij".getBytes(StandardCharsets.US_ASCII));
        ByteArrayOutputStream dst = new ByteArrayOutputStream();

        // InputStream.transferTo 是原生对应物(Java 9+);
        // FileChannel.transferTo 在文件间可能走零拷贝。
        long n = src.transferTo((OutputStream) dst);
        System.out.println("copied: " + n);
        System.out.println(dst.toString(StandardCharsets.US_ASCII));
    }
}
输出
copied: 10
abcdefghij

JavaScript v26.13.1

v26.13.1
const { Readable } = require('node:stream');

// Node 流是异步的:手动「消费-收集」循环是单调用拷贝助手
// 的显式对应。
async function main() {
  const src = Readable.from(['abcdefghij']);
  let dst = '';
  for await (const chunk of src) {
    dst += chunk;
  }
  console.log(`copied: ${Buffer.byteLength(dst)}`);
  console.log(dst);
}
main();
输出
copied: 10
abcdefghij

PHP v8.6.0

v8.6.0
$src = tmpfile();
fwrite($src, 'abcdefghij');
rewind($src);
$dst = tmpfile();
$n = stream_copy_to_stream($src, $dst); // 拷全部剩余
rewind($dst);
echo "copied: $n\n";
echo stream_get_contents($dst), "\n";

rewind($src);
$dst2 = tmpfile();
$n2 = stream_copy_to_stream($src, $dst2, 3, 4); // 偏移 4、限长 3:"efg"
rewind($dst2);
echo "partial: $n2\n";
echo stream_get_contents($dst2), "\n";
输出
copied: 10
abcdefghij
partial: 3
efg

Python v3.15.2

v3.15.2
import io
import shutil

src = io.BytesIO(b"abcdefghij")
dst = io.BytesIO()

# shutil.copyfileobj 是原生对应物:分块循环、零手动缓冲;
# 字节数由 dst.tell() 派生。
shutil.copyfileobj(src, dst)
print("copied:", dst.tell())
print(dst.getvalue().decode())
输出
copied: 10
abcdefghij

Rust v1.99.1

v1.99.1
use std::io::{self, Cursor};

fn main() {
    let mut src = Cursor::new(b"abcdefghij");
    let mut dst = Vec::new();

    // io::copy 是原生对应物:零手动缓冲,
    // 真实文件场景可用时会走零拷贝捷径。
    let n = io::copy(&mut src, &mut dst).unwrap();
    println!("copied: {}", n);
    println!("{}", String::from_utf8(dst).unwrap());
}
输出
copied: 10
abcdefghij

TypeScript v26.13.1

v26.13.1
const { Readable } = require('node:stream');

// Node 流是异步的:手动「消费-收集」循环是单调用拷贝助手
// 的显式对应。
async function main(): Promise<void> {
  const src: NodeJS.ReadableStream = Readable.from(['abcdefghij']);
  let dst = '';
  for await (const chunk of src as AsyncIterable<string>) {
    dst += chunk;
  }
  console.log(`copied: ${Buffer.byteLength(dst)}`);
  console.log(dst);
}
main();
输出
copied: 10
abcdefghij

语言差异说明

PHP:从 $from 当前位置拷到 EOF(length 限字节数;offset>0 先 fseek——0 或负数不寻址,与 stream_get_contents 的 -1 语义不同);返回实际拷贝字节数,失败返 false;移动的是两个流的游标——拷完源停在 EOF、目标停在末尾,要重读必须 rewind(手册用户注)。

内存占用:PHP 内部按块循环 read/write,拷 1GB 文件只占 O(1) 内存——这正是它优于 file_get_contents + fwrite 的地方。

socket 源注意:阻塞 socket 在 stream 超时内没收到数据时拷贝提前结束,已读部分已写入 $to 但函数可能返 false(手册 Note);8.6.0 新增可选 $context 参数。

零拷贝注(手册用户注):Linux 的 sendfile/splice 可免用户态拷贝,但 stream_copy_to_stream 并未使用 sendfile——追求极致吞吐时自行 readfile/直接 sendfile。

C/C++:stdlib 无流对流拷贝——fread/fwrite 计数循环即等价实现(示例);C++ 亦可用 istreambuf_iterator 双迭代器拷贝。

C#:Stream.CopyTo 返回 void,字节数从目标 Length(或 Position)派生。

Go:io.Copy(dst, src) (int64, error) 是原生对应——内部还会自动尝试 sendfile 等零拷贝捷径。

Java:InputStream.transferTo(OutputStream)(9+)返回 long;文件场景 FileChannel.transferTo 可能直接内核级零拷贝。

JS/TS:Node 流异步——pipeline(readStream, writeStream) 或 for-await 消费;无单次调用拷贝助手,字节数从收集结果派生。

Python:shutil.copyfileobj(src, dst, length) 返回 None,字节数用 dst.tell() 派生(示例)。

Rust:std::io::copy(&mut src, &mut dst) -> io::Result<u64> 原生对应,真实文件上内部尝试 copy_file_range/sendfile 零拷贝。