stream_get_contents
stream_get_contents(resource $stream, ?int $length = null, int $offset = -1): string|false
句柄版「读到尾」:从流当前位置读到 EOF(file_get_contents 按路径一次性读的对偶);length 限字节数、offset 可先寻址。
C C23
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *f = tmpfile(); // 匿名临时文件,fclose 时自动删除
fputs("abcdefghij", f);
fseek(f, 3, SEEK_SET);
// C 无读到尾库函数:fread 循环到 EOF 即 stream_get_contents 等价实现
char buf[64], all[128];
size_t n, len = 0;
while ((n = fread(buf, 1, sizeof(buf), f)) > 0) {
memcpy(all + len, buf, n);
len += n;
}
printf("%.*s\n", (int)len, all); // 从当前位置读到末尾
rewind(f);
n = fread(buf, 1, 4, f);
printf("%.*s\n", (int)n, buf); // 限长读取:前 4 字节
fclose(f);
return 0;
}
defghij abcd
C++ C++26
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
int main() {
std::istringstream in("abcdefghij"); // 以内存流代文件流
in.seekg(3);
// istreambuf 迭代器拷贝当前位置到末尾
std::string rest((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
std::cout << rest << "\n";
in.seekg(0);
char buf[5] = {0};
in.read(buf, 4); // 限长读取
std::cout << buf << "\n";
return 0;
}
defghij abcd
C# v11.0.100
using System.Text;
using var ms = new MemoryStream(Encoding.UTF8.GetBytes("abcdefghij"));
ms.Position = 3; // 流游标,如同 PHP 的文件位置
using (var r = new StreamReader(ms, Encoding.UTF8, leaveOpen: true)) {
Console.WriteLine(r.ReadToEnd()); // 从当前位置读到末尾
}
ms.Position = 0;
var buf = new byte[4];
ms.Read(buf, 0, 4); // 限长读取
Console.WriteLine(Encoding.UTF8.GetString(buf));
defghij abcd
Go v1.27.4
package main
import (
"fmt"
"io"
"strings"
)
func main() {
r := strings.NewReader("abcdefghij")
r.Seek(3, io.SeekStart)
rest, _ := io.ReadAll(r) // 从当前位置读到末尾
fmt.Println(string(rest))
r.Seek(0, io.SeekStart)
buf := make([]byte, 4)
r.Read(buf) // 限长读取
fmt.Println(string(buf))
}
defghij abcd
Java v27.0.1
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws java.io.IOException {
byte[] data = "abcdefghij".getBytes(StandardCharsets.UTF_8);
ByteArrayInputStream in = new ByteArrayInputStream(data);
in.skip(3);
System.out.println(new String(in.readAllBytes(), StandardCharsets.UTF_8)); // 当前位置到末尾
ByteArrayInputStream in2 = new ByteArrayInputStream(data);
byte[] buf = in2.readNBytes(4); // 限长读取
System.out.println(new String(buf, StandardCharsets.UTF_8));
}
}
defghij abcd
JavaScript v26.13.1
const fs = require("node:fs");
// fs.readSync 的 position = null 即从当前偏移读——stream_get_contents 语义
fs.writeFileSync("stream-demo.tmp", "abcdefghij");
// 以只读重新打开:游标从 0 起,如同刚 fopen() 的句柄
const fd = fs.openSync("stream-demo.tmp", "r");
fs.readSync(fd, Buffer.alloc(3), 0, 3, null); // 消费 "abc":游标推进到 3
const rest = Buffer.alloc(7);
fs.readSync(fd, rest, 0, 7, null); // null 位置:从当前位置读到末尾
console.log(rest.toString());
const head = Buffer.alloc(4);
fs.readSync(fd, head, 0, 4, 0); // 显式位置:限长读取
console.log(head.toString());
fs.closeSync(fd);
fs.rmSync("stream-demo.tmp");
defghij abcd
PHP v8.6.0
$tmp = tmpfile();
fwrite($tmp, 'abcdefghij');
fseek($tmp, 3);
echo stream_get_contents($tmp), "\n"; // 从当前位置读到剩余全部
rewind($tmp);
echo stream_get_contents($tmp, 4), "\n"; // 限长:前 4 字节
fclose($tmp);
defghij abcd
Python v3.15.2
import tempfile
with tempfile.TemporaryFile(mode="w+") as f:
f.write("abcdefghij")
f.seek(3)
print(f.read()) # 无参:从当前位置读到剩余全部
f.seek(0)
print(f.read(4)) # 限长读取
defghij abcd
Rust v1.99.1
use std::io::{Read, Seek, SeekFrom};
fn main() {
let mut c = std::io::Cursor::new("abcdefghij");
c.seek(SeekFrom::Start(3)).unwrap();
let mut rest = String::new();
c.read_to_string(&mut rest).unwrap(); // 从当前位置读到末尾
println!("{}", rest);
c.seek(SeekFrom::Start(0)).unwrap();
let mut buf = [0u8; 4];
c.read(&mut buf).unwrap(); // 限长读取
println!("{}", String::from_utf8_lossy(&buf));
}
defghij abcd
TypeScript v26.13.1
import * as fs from "node:fs";
// fs.readSync 的 position = null 即从当前偏移读——stream_get_contents 语义
fs.writeFileSync("stream-demo.tmp", "abcdefghij");
// 以只读重新打开:游标从 0 起,如同刚 fopen() 的句柄
const fd: number = fs.openSync("stream-demo.tmp", "r");
fs.readSync(fd, Buffer.alloc(3), 0, 3, null); // 消费 "abc":游标推进到 3
const rest: Buffer = Buffer.alloc(7);
fs.readSync(fd, rest, 0, 7, null); // null 位置:从当前位置读到末尾
console.log(rest.toString());
const head: Buffer = Buffer.alloc(4);
fs.readSync(fd, head, 0, 4, 0); // 显式位置:限长读取
console.log(head.toString());
fs.closeSync(fd);
fs.rmSync("stream-demo.tmp");
defghij abcd
语言差异说明
PHP:从当前位置读到 EOF 的句柄版读取(file_get_contents 按路径一次性读的对偶);length 限字节数、offset 先寻址(-1 不寻址);二进制安全(手册 Note)。
对照分工:fread($fp, n) 读固定 n 字节、fgets 读一行、stream_get_contents 读剩余。
C:无「读到尾」库函数——fread 循环到 EOF 即等价实现;tmpfile() 匿名临时文件随 fclose 自动删除。
C++:istreambuf_iterator 双迭代器构造字符串是从当前位置读到尾的惯用法;示例用 istringstream 免磁盘,ifstream 真实文件同语义。
Go:io.ReadAll 读到 EOF;Rust:Read::read_to_string;Java:InputStream.readAllBytes(Java 9+);C#:StreamReader.ReadToEnd——四家命名各异、语义相同。
JS/TS:Node fs.readSync(fd, buf, off, len, position) 的 position = null 即从当前偏移读——示例先写文件再以只读重开(游标归零)双次定位;注意指定 position 的读是 pread、不推进游标。
Python:文件对象无参 f.read() 即「读到尾」、f.read(n) 限长,无需独立函数。
注意:网络流上「读到尾」可能无限阻塞——需 stream_set_timeout/stream_select,或先查 unread_bytes(手册用户注)。