stream_copy_to_stream
stream_copy_to_stream(resource $from, resource $to, ?int $length = null, int $offset = 0, ?resource $context = null): int|false
Copies from $from's current position (seeking first when offset > 0) to EOF, capped by length, returning the byte count — large files need zero manual buffering (an internal chunked loop), and it is the native counterpart of Go's io.Copy.
C C23
#include <stdio.h>
int main(void) {
FILE *src = tmpfile();
fputs("abcdefghij", src);
rewind(src);
FILE *dst = tmpfile();
/* C stdlib has no stream-to-stream copy: a read/write loop
* that counts bytes is the portable equivalent. */
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
#include <cstdio>
int main() {
FILE *src = tmpfile();
fputs("abcdefghij", src);
rewind(src);
FILE *dst = tmpfile();
// stdio has no copy helper; the explicit counted loop is the
// portable core (iostreams would use rdbuf or streambuf iterators).
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
using System.Text;
byte[] data = Encoding.ASCII.GetBytes("abcdefghij");
using var src = new MemoryStream(data);
using var dst = new MemoryStream();
// Stream.CopyTo is the direct counterpart: zero manual buffering.
src.CopyTo(dst);
Console.WriteLine($"copied: {dst.Length}");
Console.WriteLine(Encoding.ASCII.GetString(dst.ToArray()));
copied: 10 abcdefghij
Go v1.27.4
package main
import (
"bytes"
"fmt"
"io"
)
func main() {
src := bytes.NewBufferString("abcdefghij")
var dst bytes.Buffer
// io.Copy is the native counterpart of stream_copy_to_stream;
// it may also take zero-copy shortcuts (sendfile) when possible.
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
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 is the native counterpart (Java 9+);
// FileChannel.transferTo may use zero-copy between files.
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
const { Readable } = require('node:stream');
// Node streams are async: a manual consume-and-collect loop is the
// explicit counterpart of a single-call copy helper.
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
$src = tmpfile();
fwrite($src, 'abcdefghij');
rewind($src);
$dst = tmpfile();
$n = stream_copy_to_stream($src, $dst); // copy everything left
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); // offset 4, length 3: "efg"
rewind($dst2);
echo "partial: $n2\n";
echo stream_get_contents($dst2), "\n";
copied: 10 abcdefghij partial: 3 efg
Python v3.15.2
import io
import shutil
src = io.BytesIO(b"abcdefghij")
dst = io.BytesIO()
# shutil.copyfileobj is the native counterpart: a chunked loop,
# zero manual buffering; the byte count derives from dst.tell().
shutil.copyfileobj(src, dst)
print("copied:", dst.tell())
print(dst.getvalue().decode())
copied: 10 abcdefghij
Rust v1.99.1
use std::io::{self, Cursor};
fn main() {
let mut src = Cursor::new(b"abcdefghij");
let mut dst = Vec::new();
// io::copy is the native counterpart: zero manual buffering,
// with zero-copy shortcuts for real files when available.
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
const { Readable } = require('node:stream');
// Node streams are async: a manual consume-and-collect loop is the
// explicit counterpart of a single-call copy helper.
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
Language differences
PHP: copies from $from's current position to EOF (length caps the bytes; offset > 0 seeks first — 0 or negative means no seek, unlike stream_get_contents' -1); returns the actual byte count, false on failure; both stream cursors move — afterwards the source sits at EOF and the destination at its end, so rewind before re-reading (manual user note).
Memory: PHP loops read/write internally in chunks, so copying a 1 GB file costs O(1) memory — the whole point versus file_get_contents + fwrite.
Socket sources: with a blocking socket, copying stops as soon as no data arrives within the stream timeout — bytes read so far are already written to $to yet the function may return false (manual Note); the optional $context parameter was added in 8.6.0.
Zero-copy note (manual user note): Linux sendfile/splice avoid user-space copies, but stream_copy_to_stream does not use sendfile — roll your own readfile/direct sendfile when throughput is critical.
C/C++: no stream-to-stream copy in stdlib — a counting fread/fwrite loop is the equivalent (the example); C++ can also copy via istreambuf_iterator pairs.
C#: Stream.CopyTo returns void; derive the byte count from the destination's Length (or Position).
Go: io.Copy(dst, src) (int64, error) is the native counterpart — it even tries sendfile-style zero-copy shortcuts automatically.
Java: InputStream.transferTo(OutputStream) (9+) returns a long; FileChannel.transferTo between files may be kernel-level zero-copy.
JS/TS: Node streams are async — pipeline(readStream, writeStream) or a for-await consume; no single-call copy helper, the byte count derives from what you collected.
Python: shutil.copyfileobj(src, dst, length) returns None; derive the byte count from dst.tell() (the example).
Rust: std::io::copy(&mut src, &mut dst) -> io::Result<u64> is the native counterpart; internally it tries copy_file_range/sendfile zero-copy on real files.