fread / fwrite

fread(resource $stream, int $length): string|false — fwrite(resource $stream, string $data, ?int $length = null): int|false

块的读写:fread 最多读 length 字节、fwrite 返回实际写入字节数,都可能「短」——按循环读到目标长度或 EOF 是各语言通用的流式惯用法。

C C23

C23
#include <stdio.h>

int main(void) {
    // fread/fwrite 返回传输的条目数——size 取 1 时即字节数
    FILE *h = fopen("demo.txt", "w+");
    fwrite("abcdefghij", 1, 10, h);
    fseek(h, 0, SEEK_SET);
    char buf[5];
    size_t n, total = 0;
    while ((n = fread(buf, 1, 4, h)) > 0) { // 短读在 EOF 处自然结束循环
        buf[n] = '\0';
        printf("chunk: %s\n", buf);
        total += n;
    }
    printf("total: %zu\n", total);
    fclose(h);
    return 0;
}
输出
chunk: abcd
chunk: efgh
chunk: ij
total: 10

C++ C++26

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

int main() {
    // stream.read() 的实际读取字节数通过 gcount() 报告
    std::fstream h("demo.txt", std::ios::in | std::ios::out | std::ios::trunc);
    h.write("abcdefghij", 10);
    h.seekg(0);
    char buf[5];
    std::streamsize n;
    long total = 0;
    while ((n = h.read(buf, 4).gcount()) > 0) {
        buf[n] = '\0';
        std::cout << "chunk: " << buf << "\n";
        total += n;
    }
    std::cout << "total: " << total << "\n";
}
输出
chunk: abcd
chunk: efgh
chunk: ij
total: 10

C# v11.0.100

v11.0.100
// FileStream.Read/Write 返回实际字节数——务必检查
using System.IO;
using System.Text;

FileStream h = new FileStream("demo.txt", FileMode.Create, FileAccess.ReadWrite);
byte[] data = Encoding.UTF8.GetBytes("abcdefghij");
h.Write(data, 0, 10);
h.Position = 0;
byte[] buf = new byte[4];
int n, total = 0;
while ((n = h.Read(buf, 0, 4)) > 0) {
    Console.WriteLine("chunk: " + Encoding.UTF8.GetString(buf, 0, n));
    total += n;
}
Console.WriteLine("total: " + total);
h.Close();
输出
chunk: abcd
chunk: efgh
chunk: ij
total: 10

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"os"
)

func main() {
	// File.Read 返回 (读取字节数, err);EOF 与最后一块数据同到
	h, err := os.Create("demo.txt")
	if err != nil {
		panic(err)
	}
	h.WriteString("abcdefghij")
	h.Seek(0, 0)
	buf := make([]byte, 4)
	total := 0
	for {
		n, err := h.Read(buf)
		if n > 0 {
			fmt.Printf("chunk: %s\n", buf[:n])
			total += n
		}
		if err != nil {
			break // io.EOF 结束流
		}
	}
	fmt.Printf("total: %d\n", total)
	h.Close()
}
输出
chunk: abcd
chunk: efgh
chunk: ij
total: 10

Java v27.0.1

v27.0.1
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) throws Exception {
        // InputStream.read 返回实际读取字节数;越过 EOF 才返回 -1
        FileOutputStream o = new FileOutputStream("demo.txt");
        o.write("abcdefghij".getBytes(StandardCharsets.UTF_8));
        o.close();
        FileInputStream h = new FileInputStream("demo.txt");
        byte[] buf = new byte[4];
        int n, total = 0;
        while ((n = h.read(buf)) > 0) {
            System.out.println("chunk: " + new String(buf, 0, n, StandardCharsets.UTF_8));
            total += n;
        }
        System.out.println("total: " + total);
        h.close();
    }
}
输出
chunk: abcd
chunk: efgh
chunk: ij
total: 10

JavaScript v26.13.1

v26.13.1
// fs.readSync 返回实际读取字节数;定位读需要手动维护偏移
const fs = require("node:fs");
const h = fs.openSync("demo.txt", "w+");
fs.writeSync(h, "abcdefghij");
const buf = Buffer.alloc(4);
let total = 0, off = 0;
for (;;) {
    const n = fs.readSync(h, buf, 0, 4, off);
    if (n === 0) break;
    console.log("chunk:", buf.subarray(0, n).toString());
    total += n;
    off += n;
}
console.log("total:", total);
fs.closeSync(h);
输出
chunk: abcd
chunk: efgh
chunk: ij
total: 10

PHP v8.6.0

v8.6.0
// fread 最多返回 $length 字节且可能短读;循环到 feof() 为止
$h = fopen("demo.txt", "w+");
fwrite($h, "abcdefghij");
fseek($h, 0);
$total = 0;
while (!feof($h)) {
    $chunk = fread($h, 4);
    if ($chunk === false || $chunk === "") break;
    echo "chunk: $chunk\n";
    $total += strlen($chunk);
}
echo "total: $total\n";
fclose($h);
输出
chunk: abcd
chunk: efgh
chunk: ij
total: 10

Python v3.15.2

v3.15.2
# read(n) 最多返回 n 字节;b"" 即 EOF——各语言同样的循环形态
with open("demo.txt", "w+b") as h:
    h.write(b"abcdefghij")
    h.seek(0)
    total = 0
    while True:
        chunk = h.read(4)
        if not chunk:
            break
        print(f"chunk: {chunk.decode()}")
        total += len(chunk)
    print(f"total: {total}")
输出
chunk: abcd
chunk: efgh
chunk: ij
total: 10

Rust v1.99.1

v1.99.1
use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom, Write};

fn main() {
    // Read::read 可能只填满缓冲区的一部分,返回 Ok(实际字节数)
    //(File::create 只写——读写句柄要用 OpenOptions)
    let mut h = OpenOptions::new().read(true).write(true).create(true).truncate(true).open("demo.txt").unwrap();
    h.write_all(b"abcdefghij").unwrap();
    h.seek(SeekFrom::Start(0)).unwrap();
    let mut buf = [0u8; 4];
    let mut total = 0usize;
    loop {
        match h.read(&mut buf) {
            Ok(0) => break, // EOF
            Ok(n) => {
                println!("chunk: {}", String::from_utf8_lossy(&buf[..n]));
                total += n;
            }
            Err(_) => break,
        }
    }
    println!("total: {}", total);
}
输出
chunk: abcd
chunk: efgh
chunk: ij
total: 10

TypeScript v26.13.1

v26.13.1
// fs.readSync 返回实际读取字节数;定位读需要手动维护偏移
import * as fs from "node:fs";
const h = fs.openSync("demo.txt", "w+");
fs.writeSync(h, "abcdefghij");
const buf: Buffer = Buffer.alloc(4);
let total = 0, off = 0;
for (;;) {
    const n: number = fs.readSync(h, buf, 0, 4, off);
    if (n === 0) break;
    console.log("chunk:", buf.subarray(0, n).toString());
    total += n;
    off += n;
}
console.log("total:", total);
fs.closeSync(h);
输出
chunk: abcd
chunk: efgh
chunk: ij
total: 10

语言差异说明

C:fread/fwrite 返回传输条目数,size 取 1 时即字节数;短读是正常行为。

C++:read 的返回值是流引用,实际字节数看 gcount()。

C#:Read/Write 直接返回实际字节数;网络流上必须按返回值循环写。

Go:Read 返回 (n, err),EOF 与最后一段数据同到——先处理 n 再判断 err。

Java:InputStream.read 返回实际字节数,-1 表示越过 EOF。

JavaScript:Node 定位读的 position 参数不移动文件指针,偏移要自己累加。

PHP:fread 最多读 length 字节;网络流上常短读(一个包),文件流按块读满;写循环要检查 fwrite 返回值(管道断开时会返回 0 而非 false)。

Python:read(n) 在原始流上通常读满,但协议层不保证——循环判空串才是 EOF 的正解。

Rust:read 只承诺「至多」填满缓冲区,Ok(0) 才是 EOF。

TypeScript:同 JavaScript。