splfileobject
SplFileObject extends SplFileInfo implements RecursiveIterator, SeekableIterator
The SPL object-oriented way to read files: foreach iterates lines directly (key is the line number, current the line), seek jumps to a line, setFlags(DROP_NEW_LINE) strips trailing newlines — a dual-track counterpart to procedural fopen/fgets, another stop on PHP's "procedural vs OOP" theme.
C C23
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("demo.txt", "w");
fputs("alpha\nbeta\ngamma", fp);
fclose(fp);
char line[64];
char out[256] = "";
int i = 0;
fp = fopen("demo.txt", "r");
while (fgets(line, sizeof line, fp)) { /* read line by line */
line[strcspn(line, "\n")] = 0; /* strip the trailing newline */
if (i > 0) strcat(out, " ");
char buf[80];
sprintf(buf, "%d:%s", i, line);
strcat(out, buf);
i++;
}
fclose(fp);
printf("%s\n", out);
fp = fopen("demo.txt", "r");
fgets(line, sizeof line, fp); /* skip line 0 */
fgets(line, sizeof line, fp);
line[strcspn(line, "\n")] = 0;
printf("1=%s\n", line);
fclose(fp);
remove("demo.txt");
return 0;
}
0:alpha 1:beta 2:gamma 1=beta
C++ C++26
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
int main() {
{
std::ofstream out("demo.txt");
out << "alpha\nbeta\ngamma";
}
std::ifstream in("demo.txt");
std::string line;
std::string res;
int i = 0;
while (std::getline(in, line)) { // read line by line
if (i > 0) res += " ";
res += std::to_string(i) + ":" + line;
i++;
}
in.clear();
in.seekg(0);
std::getline(in, line); // skip line 0
std::getline(in, line);
std::cout << res << "\n";
std::cout << "1=" << line << "\n";
in.close();
std::remove("demo.txt");
return 0;
}
0:alpha 1:beta 2:gamma 1=beta
C# v11.0.100
using System;
using System.IO;
using System.Linq;
File.WriteAllText("demo.txt", "alpha\nbeta\ngamma");
// File.ReadLines: a lazy line iterator — the direct counterpart of foreach
Console.WriteLine(string.Join(" ", File.ReadLines("demo.txt").Select((l, i) => $"{i}:{l}")));
Console.WriteLine($"1={File.ReadLines("demo.txt").Skip(1).First()}");
File.Delete("demo.txt");
0:alpha 1:beta 2:gamma 1=beta
Go v1.27.4
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
os.WriteFile("demo.txt", []byte("alpha\nbeta\ngamma"), 0o600)
// bufio.Scanner splits the file into lines
f, _ := os.Open("demo.txt")
scanner := bufio.NewScanner(f)
parts := []string{}
i := 0
for scanner.Scan() {
parts = append(parts, fmt.Sprintf("%d:%s", i, scanner.Text()))
i++
}
f.Close()
fmt.Println(strings.Join(parts, " "))
f, _ = os.Open("demo.txt")
scanner = bufio.NewScanner(f)
scanner.Scan() // skip line 0
scanner.Scan()
fmt.Printf("1=%s\n", scanner.Text())
f.Close()
os.Remove("demo.txt")
}
0:alpha 1:beta 2:gamma 1=beta
Java v27.0.1
import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
Path p = Path.of("demo.txt");
Files.writeString(p, "alpha\nbeta\ngamma");
try (BufferedReader br = new BufferedReader(new FileReader(p.toFile()))) {
StringBuilder sb = new StringBuilder();
String line;
int i = 0;
while ((line = br.readLine()) != null) { // read line by line
if (i > 0) sb.append(" ");
sb.append(i).append(":").append(line);
i++;
}
System.out.println(sb);
}
try (BufferedReader br = new BufferedReader(new FileReader(p.toFile()))) {
br.readLine(); // skip line 0
System.out.println("1=" + br.readLine());
}
Files.deleteIfExists(p);
}
}
0:alpha 1:beta 2:gamma 1=beta
JavaScript v26.13.1
const fs = require("node:fs");
const readline = require("node:readline");
const { once } = require("node:events");
(async () => {
fs.writeFileSync("demo.txt", "alpha\nbeta\ngamma");
// readline turns a file into a line-by-line event stream
const rl = readline.createInterface({ input: fs.createReadStream("demo.txt") });
const parts = [];
let i = 0;
rl.on("line", (line) => parts.push(`${i++}:${line}`));
await once(rl, "close");
console.log(parts.join(" "));
const lines = fs.readFileSync("demo.txt", "utf8").split("\n");
console.log(`1=${lines[1]}`);
fs.unlinkSync("demo.txt");
})();
0:alpha 1:beta 2:gamma 1=beta
PHP v8.6.0
$path = tempnam(sys_get_temp_dir(), "spl");
file_put_contents($path, "alpha\nbeta\ngamma");
$file = new SplFileObject($path, "r");
$file->setFlags(SplFileObject::DROP_NEW_LINE);
$out = [];
foreach ($file as $no => $line) { // iterate lines like an array: key() + current()
$out[] = "$no:$line";
}
echo implode(" ", $out), "\n";
$file->seek(1); // jump to line 1
echo $file->key(), "=", $file->current(), "\n";
$fp = fopen($path, "r"); // the procedural twin
echo fgets($fp);
fclose($fp);
unlink($path);
0:alpha 1:beta 2:gamma 1=beta alpha
Python v3.15.2
# file objects iterate lines natively — the direct counterpart of foreach
with open("demo.txt", "w") as fp:
fp.write("alpha\nbeta\ngamma")
with open("demo.txt") as f:
print(" ".join(f"{i}:{line.strip()}" for i, line in enumerate(f)))
with open("demo.txt") as f:
f.readline() # skip line 0
print(f"1={f.readline().strip()}")
import os
os.unlink("demo.txt")
0:alpha 1:beta 2:gamma 1=beta
Rust v1.99.1
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
fn main() -> std::io::Result<()> {
File::create("demo.txt")?.write_all(b"alpha\nbeta\ngamma")?;
// BufReader::lines: an iterator over lines — the direct counterpart
let reader = BufReader::new(File::open("demo.txt")?);
let parts: Vec<String> = reader
.lines()
.enumerate()
.map(|(i, l)| format!("{}:{}", i, l.unwrap()))
.collect();
println!("{}", parts.join(" "));
let mut reader = BufReader::new(File::open("demo.txt")?);
let mut buf = String::new();
reader.read_line(&mut buf)?; // skip line 0
buf.clear();
reader.read_line(&mut buf)?;
println!("1={}", buf.trim_end());
std::fs::remove_file("demo.txt")?;
Ok(())
}
0:alpha 1:beta 2:gamma 1=beta
TypeScript v26.13.1
import * as fs from "node:fs";
import * as readline from "node:readline";
import { once } from "node:events";
(async (): Promise<void> => {
fs.writeFileSync("demo.txt", "alpha\nbeta\ngamma");
// readline turns a file into a line-by-line event stream
const rl = readline.createInterface({ input: fs.createReadStream("demo.txt") });
const parts: string[] = [];
let i = 0;
rl.on("line", (line: string) => parts.push(`${i++}:${line}`));
await once(rl, "close");
console.log(parts.join(" "));
const lines: string[] = fs.readFileSync("demo.txt", "utf8").split("\n");
console.log(`1=${lines[1]}`);
fs.unlinkSync("demo.txt");
})();
0:alpha 1:beta 2:gamma 1=beta
Language differences
C: line-by-line fgets + strcspn to strip the newline — a bare procedural loop where you count lines yourself.
C++: std::getline(ifstream, line) per line — cleaner than C but still manual, rewound with seekg(0).
C#: File.ReadLines is a lazy line iterator — with LINQ Select((l, i)) numbering lines directly, the straightest counterpart of foreach.
Go: bufio.Scanner scans line by line (64KB line limit by default; enlarge via Buffer), pairing Scan() with Text().
Java: a BufferedReader.readLine loop; try-with-resources closes the stream automatically.
JavaScript: readline turns the file into a per-line event stream (the event-style counterpart); the synchronous fallback is readFileSync().split("\n").
PHP: SplFileObject is the SPL way to read files OOP-style: foreach iterates lines directly (each round gives key() as the line number and current() as the line), seek(N) jumps to a line, and setFlags(DROP_NEW_LINE) strips trailing newlines. Two gotchas: a file ending in \n makes foreach emit one extra empty line (the famous lazy-eof quirk — the demo deliberately omits the trailing newline), and the object holds the file handle with no close method, so unlink before destruction fails. It runs dual-track with the procedural fopen/fgets style — another stop on PHP's dual-API theme. Since 8.6 the fgetcsv()/fputcsv()/getCsvControl()/setCsvControl() methods are deprecated (use the standalone functions instead).
Python: file objects are natively iterable — enumerate(f) is "line number + line", the most direct counterpart.
Rust: BufReader::lines() returns a line iterator (each item an io::Result<String>) — a direct counterpart.
TypeScript: same JS readline event stream; the main function is typed Promise<void>.