splfileobject

SplFileObject extends SplFileInfo implements RecursiveIterator, SeekableIterator

SPL 的 OOP 文件读取:foreach 直接迭代行(key 行号/current 行内容),seek 跳行,setFlags(DROP_NEW_LINE) 去尾换行——与 fopen/fgets 过程式双轨并行,是 PHP「过程式/OOP 双轨」主题的又一站。

C C23

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)) { /* 逐行读取 */
        line[strcspn(line, "\n")] = 0;    /* 剥掉行尾换行 */
        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); /* 跳过第 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

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)) { // 逐行读取
        if (i > 0) res += " ";
        res += std::to_string(i) + ":" + line;
        i++;
    }
    in.clear();
    in.seekg(0);
    std::getline(in, 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

v11.0.100
using System;
using System.IO;
using System.Linq;

File.WriteAllText("demo.txt", "alpha\nbeta\ngamma");

// File.ReadLines:惰性行迭代器——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

v1.27.4
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	os.WriteFile("demo.txt", []byte("alpha\nbeta\ngamma"), 0o600)

	// bufio.Scanner 把文件按行切开
	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() // 跳过第 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

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) { // 逐行读取
                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();                 // 跳过第 0 行
            System.out.println("1=" + br.readLine());
        }
        Files.deleteIfExists(p);
    }
}
输出
0:alpha 1:beta 2:gamma
1=beta

JavaScript v26.13.1

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 把文件变成逐行事件流
  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

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) { // 像数组一样迭代行:key() + current()
    $out[] = "$no:$line";
}
echo implode(" ", $out), "\n";
$file->seek(1);                   // 跳到第 1 行
echo $file->key(), "=", $file->current(), "\n";
$fp = fopen($path, "r");          // 过程式对照
echo fgets($fp);
fclose($fp);
unlink($path);
输出
0:alpha 1:beta 2:gamma
1=beta
alpha

Python v3.15.2

v3.15.2
# 文件对象原生可迭代——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()                        # 跳过第 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

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:行迭代器——foreach 的最直接对应
    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)?; // 跳过第 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

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 把文件变成逐行事件流
  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

语言差异说明

C:fgets 逐行 + strcspn 剥换行——过程式裸循环,行号要自己数。

C++:std::getline(ifstream, line) 逐行——比 C 干净但仍手动,配合 seekg(0) 回卷。

C#:File.ReadLines 惰性行迭代器 + LINQ Select((l, i)) 直接编号——foreach 的最直对照。

Go:bufio.Scanner 按行扫描(默认 64KB 行上限,超长需改 Buffer),Scan()/Text() 配对使用。

Java:BufferedReader.readLine 循环;try-with-resources 自动关流。

JavaScript:readline 把文件变成「行事件」流(事件式对照);同步兜底用 readFileSync().split("\n")。

PHP:SplFileObject 是 SPL 的 OOP 文件读取:foreach 直接迭代行(每轮 key() 行号 / current() 行内容),seek(N) 跳行,setFlags(DROP_NEW_LINE) 去行尾换行。两个要点:文件以 \n 结尾时 foreach 会多吐一个空行(eof 惰性检查的著名怪癖,示例故意不写尾换行);对象持有文件句柄且无关闭方法,销毁前 unlink 会失败。与 fopen/fgets 过程式写法双轨——PHP 文件 API 双轨制的又一站。8.6 起 fgetcsv()/fputcsv()/getCsvControl()/setCsvControl() 方法被弃用(改用同名函数)。

Python:文件对象原生可迭代——enumerate(f) 即「行号 + 行」,最直接对应。

Rust:BufReader::lines() 返回行迭代器(每行是 io::Result<String>)——直接对应。

TypeScript:同 JS readline 事件流,主函数标注 Promise<void>。