fseek / ftell

fseek(resource $stream, int $offset, int $whence = SEEK_SET): int — ftell(resource $stream): int|false

Random access: SEEK_SET/CUR/END whences paired with ftell - the basics of jumping around large files and locating in logs; SEEK_END needs a NEGATIVE offset to land before the end of file.

C C23

C23
#include <stdio.h>

int main(void) {
    // fseek returns 0 on success / -1 on failure - C-style, not PHP's false
    FILE *h = fopen("demo.txt", "w+");
    fwrite("0123456789", 1, 10, h);
    fseek(h, 0, SEEK_SET);
    char buf[8] = {0};
    size_t n = fread(buf, 1, 2, h);
    printf("first2: %s pos: %ld\n", buf, ftell(h));
    fseek(h, -1, SEEK_CUR); // step back one byte
    n = fread(buf, 1, 2, h);
    buf[n] = '\0';
    printf("back1: %s pos: %ld\n", buf, ftell(h));
    fseek(h, -4, SEEK_END); // tail read: the last 4 bytes
    n = fread(buf, 1, 4, h);
    buf[n] = '\0';
    printf("end-4: %s\n", buf);
    fseek(h, 0, SEEK_SET);
    printf("rewind: %ld\n", ftell(h));
    fclose(h);
    return 0;
}
Output
first2: 01 pos: 2
back1: 12 pos: 3
end-4: 6789
rewind: 0

C++ C++26

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

int main() {
    // seekg/tellg move and report the get (read) position; seekp/tellp are the put side
    std::fstream h("demo.txt", std::ios::in | std::ios::out | std::ios::trunc);
    h.write("0123456789", 10);
    h.seekg(0, std::ios_base::beg);
    char buf[8] = {0};
    h.read(buf, 2);
    std::cout << "first2: " << buf << " pos: " << h.tellg() << "\n";
    h.seekg(-1, std::ios_base::cur);
    h.read(buf, 2);
    std::cout << "back1: " << buf << " pos: " << h.tellg() << "\n";
    h.seekg(-4, std::ios_base::end);
    h.read(buf, 4);
    std::cout << "end-4: " << buf << "\n";
    h.seekg(0, std::ios_base::beg);
    std::cout << "rewind: " << h.tellg() << "\n";
}
Output
first2: 01 pos: 2
back1: 12 pos: 3
end-4: 6789
rewind: 0

C# v11.0.100

v11.0.100
// FileStream.Seek(offset, SeekOrigin) + Position property
using System.IO;
using System.Text;

FileStream h = new FileStream("demo.txt", FileMode.Create, FileAccess.ReadWrite);
h.Write(Encoding.UTF8.GetBytes("0123456789"), 0, 10);
h.Position = 0;
byte[] buf = new byte[8];
int n = h.Read(buf, 0, 2);
Console.WriteLine("first2: " + Encoding.UTF8.GetString(buf, 0, n) + " pos: " + h.Position);
h.Seek(-1, SeekOrigin.Current);
n = h.Read(buf, 0, 2);
Console.WriteLine("back1: " + Encoding.UTF8.GetString(buf, 0, n) + " pos: " + h.Position);
h.Seek(-4, SeekOrigin.End);
n = h.Read(buf, 0, 4);
Console.WriteLine("end-4: " + Encoding.UTF8.GetString(buf, 0, n));
h.Seek(0, SeekOrigin.Begin);
Console.WriteLine("rewind: " + h.Position);
h.Close();
Output
first2: 01 pos: 2
back1: 12 pos: 3
end-4: 6789
rewind: 0

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
	// os.File.Seek(offset, whence) mirrors SEEK_SET/CUR/END; ftell = Seek(0, SeekCurrent)
	f, err := os.Create("demo.txt")
	if err != nil {
		panic(err)
	}
	f.WriteString("0123456789")
	f.Seek(0, io.SeekStart)
	buf := make([]byte, 8)
	n, _ := f.Read(buf[:2])
	pos, _ := f.Seek(0, io.SeekCurrent)
	fmt.Printf("first2: %s pos: %d\n", buf[:n], pos)
	f.Seek(-1, io.SeekCurrent)
	n, _ = f.Read(buf[:2])
	pos, _ = f.Seek(0, io.SeekCurrent)
	fmt.Printf("back1: %s pos: %d\n", buf[:n], pos)
	f.Seek(-4, io.SeekEnd)
	n, _ = f.Read(buf[:4])
	fmt.Printf("end-4: %s\n", buf[:n])
	f.Seek(0, io.SeekStart)
	pos, _ = f.Seek(0, io.SeekCurrent)
	fmt.Printf("rewind: %d\n", pos)
	f.Close()
}
Output
first2: 01 pos: 2
back1: 12 pos: 3
end-4: 6789
rewind: 0

Java v27.0.1

v27.0.1
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) throws Exception {
        // RandomAccessFile is THE random-access handle: seek() + getFilePointer()
        RandomAccessFile h = new RandomAccessFile("demo.txt", "rw");
        h.write("0123456789".getBytes(StandardCharsets.UTF_8));
        h.seek(0);
        byte[] buf = new byte[8];
        int n = h.read(buf, 0, 2);
        System.out.println("first2: " + new String(buf, 0, n, StandardCharsets.UTF_8) + " pos: " + h.getFilePointer());
        h.seek(h.getFilePointer() - 1); // SEEK_CUR - 1
        n = h.read(buf, 0, 2);
        System.out.println("back1: " + new String(buf, 0, n, StandardCharsets.UTF_8) + " pos: " + h.getFilePointer());
        h.seek(h.length() - 4); // SEEK_END - 4
        n = h.read(buf, 0, 4);
        System.out.println("end-4: " + new String(buf, 0, n, StandardCharsets.UTF_8));
        h.seek(0); // SEEK_SET 0
        System.out.println("rewind: " + h.getFilePointer());
        h.close();
    }
}
Output
first2: 01 pos: 2
back1: 12 pos: 3
end-4: 6789
rewind: 0

JavaScript v26.13.1

v26.13.1
// Node positioned reads take an ABSOLUTE offset - there is no SEEK_CUR/ftell;
// emulate the three whences by tracking the offset yourself
const fs = require("node:fs");
const h = fs.openSync("demo.txt", "w+");
fs.writeSync(h, "0123456789");
let pos = 0;
const buf = Buffer.alloc(8);
let n = fs.readSync(h, buf, 0, 2, pos); // SEEK_SET 0
pos += n;
console.log(`first2: ${buf.subarray(0, n)} pos: ${pos}`);
pos += -1; // SEEK_CUR with a negative delta
n = fs.readSync(h, buf, 0, 2, pos);
pos += n;
console.log(`back1: ${buf.subarray(0, n)} pos: ${pos}`);
n = fs.readSync(h, buf, 0, 4, 10 - 4); // SEEK_END - 4 (file size is known: 10)
pos = 10;
console.log(`end-4: ${buf.subarray(0, n)}`);
pos = 0; // SEEK_SET 0
console.log(`rewind: ${pos}`);
fs.closeSync(h);
Output
first2: 01 pos: 2
back1: 12 pos: 3
end-4: 6789
rewind: 0

PHP v8.6.0

v8.6.0
// fseek returns 0 on success / -1 on failure (C-style, unlike PHP's usual false);
// SEEK_END only lands BEFORE the end of file with a NEGATIVE offset
$h = fopen("demo.txt", "w+");
fwrite($h, "0123456789");
fseek($h, 0, SEEK_SET);
$s = fread($h, 2);
echo "first2: $s pos: ", ftell($h), "\n";
fseek($h, -1, SEEK_CUR);
$s = fread($h, 2);
echo "back1: $s pos: ", ftell($h), "\n";
fseek($h, -4, SEEK_END); // tail read: the last 4 bytes
echo "end-4: ", fread($h, 4), "\n";
fseek($h, 0, SEEK_SET);
echo "rewind: ", ftell($h), "\n";
fclose($h);
Output
first2: 01 pos: 2
back1: 12 pos: 3
end-4: 6789
rewind: 0

Python v3.15.2

v3.15.2
# seek(offset, whence): 0=SEEK_SET, 1=SEEK_CUR, 2=SEEK_END; tell() is ftell
with open("demo.txt", "w+b") as h:
    h.write(b"0123456789")
    h.seek(0) # SEEK_SET
    s = h.read(2)
    print(f"first2: {s.decode()} pos: {h.tell()}")
    h.seek(-1, 1) # SEEK_CUR with a negative step
    s = h.read(2)
    print(f"back1: {s.decode()} pos: {h.tell()}")
    h.seek(-4, 2) # SEEK_END with a negative step
    print(f"end-4: {h.read(4).decode()}")
    h.seek(0)
    print(f"rewind: {h.tell()}")
Output
first2: 01 pos: 2
back1: 12 pos: 3
end-4: 6789
rewind: 0

Rust v1.99.1

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

fn main() {
    // SeekFrom::{Start,Current,End} typed whences; stream_position() is ftell
    // (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"0123456789").unwrap();
    let mut buf = [0u8; 8];
    h.seek(SeekFrom::Start(0)).unwrap();
    let n = h.read(&mut buf[..2]).unwrap();
    println!("first2: {} pos: {}", String::from_utf8_lossy(&buf[..n]), h.stream_position().unwrap());
    h.seek(SeekFrom::Current(-1)).unwrap();
    let n = h.read(&mut buf[..2]).unwrap();
    println!("back1: {} pos: {}", String::from_utf8_lossy(&buf[..n]), h.stream_position().unwrap());
    h.seek(SeekFrom::End(-4)).unwrap();
    let n = h.read(&mut buf[..4]).unwrap();
    println!("end-4: {}", String::from_utf8_lossy(&buf[..n]));
    h.seek(SeekFrom::Start(0)).unwrap();
    println!("rewind: {}", h.stream_position().unwrap());
}
Output
first2: 01 pos: 2
back1: 12 pos: 3
end-4: 6789
rewind: 0

TypeScript v26.13.1

v26.13.1
// Node positioned reads take an ABSOLUTE offset - emulate the three whences manually
import * as fs from "node:fs";
const h = fs.openSync("demo.txt", "w+");
fs.writeSync(h, "0123456789");
let pos = 0;
const buf: Buffer = Buffer.alloc(8);
let n: number = fs.readSync(h, buf, 0, 2, pos); // SEEK_SET 0
pos += n;
console.log(`first2: ${buf.subarray(0, n)} pos: ${pos}`);
pos += -1; // SEEK_CUR with a negative delta
n = fs.readSync(h, buf, 0, 2, pos);
pos += n;
console.log(`back1: ${buf.subarray(0, n)} pos: ${pos}`);
n = fs.readSync(h, buf, 0, 4, 10 - 4); // SEEK_END - 4
pos = 10;
console.log(`end-4: ${buf.subarray(0, n)}`);
pos = 0;
console.log(`rewind: ${pos}`);
fs.closeSync(h);
Output
first2: 01 pos: 2
back1: 12 pos: 3
end-4: 6789
rewind: 0

Language differences

C: fseek returns 0 on success / -1 on failure (same as PHP); ftell returns long - use ftello for large files.

C++: seekg/tellg handle the read side and seekp/tellp the write side - two independent positions.

C#: Seek(offset, SeekOrigin) matches PHP exactly; the Position property is readable and writable.

Go: Seek takes io.SeekStart/Current/End as whence; query the current position with Seek(0, io.SeekCurrent).

Java: RandomAccessFile.seek() is absolute-only; SEEK_CUR/END effects must be computed via getFilePointer()/length() - this sample shows exactly that.

JavaScript: the positioned-read argument is absolute and does not move the file pointer - all three whences are manual offset bookkeeping.

PHP: SEEK_END with a POSITIVE offset lands past EOF (reads yield NUL bytes) - tail reads need a negative offset; in append mode (a/a+) fseek has no effect on writes.

Python: text mode allows only a few seek combinations (like seek(0, ...)); random access requires binary mode.

Rust: SeekFrom turns the three whences into types - illegal whence values are compile-time errors.

TypeScript: same as JavaScript.