fread / fwrite
fread(resource $stream, int $length): string|false — fwrite(resource $stream, string $data, ?int $length = null): int|false
Block read/write: fread reads up to length bytes and fwrite returns the bytes actually written - both can come up short, so loop-until-full-or-EOF is the cross-language streaming idiom.
C C23
#include <stdio.h>
int main(void) {
// fread/fwrite return the ITEMS transferred - with size 1, that is bytes
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) { // short reads end the loop at 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
#include <fstream>
#include <iostream>
int main() {
// stream.read() reports the actual count via 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
// FileStream.Read/Write return the ACTUAL byte counts - always check them
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
package main
import (
"fmt"
"os"
)
func main() {
// File.Read returns (bytesRead, err); io.EOF arrives with the final chunk
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 ends the stream
}
}
fmt.Printf("total: %d\n", total)
h.Close()
}
chunk: abcd chunk: efgh chunk: ij total: 10
Java 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 returns the actual bytes read, -1 only past EOF
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
// fs.readSync returns the bytes actually read; positioned reads need a manual offset
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
// fread returns up to $length bytes and may short-read; loop until 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
# read(n) returns up to n bytes; b"" marks EOF - same loop shape everywhere
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
use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom, Write};
fn main() {
// Read::read fills the buffer partially and returns Ok(bytesRead)
// (File::create is write-only - a read+write handle needs 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
// fs.readSync returns the bytes actually read; positioned reads need a manual offset
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
Language differences
C: fread/fwrite return transferred item counts - with size 1 that is bytes; short reads are normal.
C++: read returns a stream reference; the actual byte count lives in gcount().
C#: Read/Write return the actual byte counts; on network streams you must loop writes by the return value.
Go: Read returns (n, err) - EOF arrives together with the final chunk, so handle n before checking err.
Java: InputStream.read returns the actual byte count; -1 means past EOF.
JavaScript: Node's positioned read takes a position argument that does NOT advance the file pointer - track the offset yourself.
PHP: fread reads at most length bytes; network streams often short-read (one packet), file streams fill the chunk; check fwrite's return in write loops (a broken pipe yields 0, not false).
Python: read(n) usually fills on raw streams but nothing guarantees it at the protocol level - an empty bytes is the real EOF signal.
Rust: read only promises to fill the buffer AT MOST; Ok(0) is EOF.
TypeScript: same as JavaScript.