fgets

fgets(resource $stream, ?int $length = null): string|false

逐行读取:PHP fgets 把行尾换行符保留在返回值里(length-1 上限),EOF 返回 false——与各语言「是否含换行」的语义差是核心教学点。

C C23

C23
#include <stdio.h>

int main(void) {
    // fgets 保留行尾 "\n"(上限 length-1 字节)——PHP 继承了这个语义
    FILE *w = fopen("demo.txt", "w");
    fputs("alpha\nbeta\ngamma", w);
    fclose(w);

    FILE *h = fopen("demo.txt", "r");
    char line[32];
    int count = 0;
    while (fgets(line, sizeof line, h) != NULL) {
        count++;
        printf("line %d: ", count);
        for (char *p = line; *p != '\0'; p++) {
            if (*p == '\n') {
                printf("\\n"); // 把保留的换行显示出来
            } else {
                putchar(*p);
            }
        }
        printf("\n");
    }
    fclose(h);
    return 0;
}
输出
line 1: alpha\n
line 2: beta\n
line 3: gamma

C++ C++26

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

int main() {
    // std::getline 剥掉 "\n"——与 fgets 正相反的选择
    {
        std::ofstream w("demo.txt");
        w << "alpha\nbeta\ngamma";
    }
    std::ifstream h("demo.txt");
    std::string line;
    int count = 0;
    while (std::getline(h, line)) {
        count++;
        std::cout << "line " << count << ": " << line;
        if (!h.eof()) {
            std::cout << "\\n"; // 非 EOF 的行原本以换行结尾,只是被 getline 剥掉了
        }
        std::cout << "\n";
    }
}
输出
line 1: alpha\n
line 2: beta\n
line 3: gamma

C# v11.0.100

v11.0.100
// StreamReader.ReadLine 剥掉换行;Peek() 可判断是否还有后续数据
using System.IO;

File.WriteAllText("demo.txt", "alpha\nbeta\ngamma");
using (StreamReader r = new StreamReader("demo.txt")) {
    int count = 0;
    string? line;
    while ((line = r.ReadLine()) != null) {
        count++;
        bool hadNl = r.Peek() != -1; // 还有数据说明本行以 "\n" 结尾
        Console.WriteLine($"line {count}: {line}{(hadNl ? "\\n" : "")}");
    }
}
输出
line 1: alpha\n
line 2: beta\n
line 3: gamma

Go v1.27.4

v1.27.4
package main

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

func main() {
	// bufio.Reader.ReadString 保留分隔符——正是 fgets 的行为
	f, _ := os.Create("demo.txt")
	f.WriteString("alpha\nbeta\ngamma")
	f.Close()

	f, _ = os.Open("demo.txt")
	defer f.Close()
	reader := bufio.NewReader(f)
	count := 0
	for {
		line, err := reader.ReadString('\n') // 保留 "\n"
		if len(line) > 0 {
			count++
			marker := ""
			if strings.HasSuffix(line, "\n") {
				marker = "\\n"
			}
			fmt.Printf("line %d: %s%s\n", count, strings.TrimSuffix(line, "\n"), marker)
		}
		if err != nil {
			break // 最后一行(无换行)之后是 io.EOF
		}
	}
}
输出
line 1: alpha\n
line 2: beta\n
line 3: gamma

Java v27.0.1

v27.0.1
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws Exception {
        // BufferedReader.readLine 剥掉换行;ready() 报告是否还有数据
        Files.writeString(Path.of("demo.txt"), "alpha\nbeta\ngamma");
        BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream("demo.txt"), StandardCharsets.UTF_8));
        int count = 0;
        String line;
        while ((line = r.readLine()) != null) {
            count++;
            String marker = r.ready() ? "\\n" : ""; // 还有数据说明本行以 "\n" 结尾
            System.out.println("line " + count + ": " + line + marker);
        }
        r.close();
    }
}
输出
line 1: alpha\n
line 2: beta\n
line 3: gamma

JavaScript v26.13.1

v26.13.1
// Node 没有像 fgets 那样的行迭代器;确定性的等价做法是按 "\n" 切分
const fs = require("node:fs");
fs.writeFileSync("demo.txt", "alpha\nbeta\ngamma");
const content = fs.readFileSync("demo.txt", "utf8");
const lines = content.split("\n"); // 此处没有结尾 "\n",不会产生空尾巴段
lines.forEach((line, i) => {
    const hadNl = i < lines.length - 1; // 除最后一段外,每段都以 "\n" 结尾
    console.log(`line ${i + 1}: ${line}${hadNl ? "\\n" : ""}`);
});
输出
line 1: alpha\n
line 2: beta\n
line 3: gamma

PHP v8.6.0

v8.6.0
// fgets 的返回值包含行尾 "\n"(除非被 EOF 截断)
file_put_contents("demo.txt", "alpha\nbeta\ngamma");
$h = fopen("demo.txt", "r");
$count = 0;
while (($line = fgets($h)) !== false) {
    $count++;
    $hadNl = str_ends_with($line, "\n"); // PHP 保留换行——与多数语言相反
    echo "line $count: ", rtrim($line, "\n"), $hadNl ? "\\n" : "", "\n";
}
fclose($h);
输出
line 1: alpha\n
line 2: beta\n
line 3: gamma

Python v3.15.2

v3.15.2
# 迭代文件对象得到的行保留 "\n"——与 fgets 同构
with open("demo.txt", "w") as f:
    f.write("alpha\nbeta\ngamma")
with open("demo.txt") as f:
    for count, line in enumerate(f, 1):
        had_nl = line.endswith("\n")  # 与 fgets 一样保留换行
        marker = "\\n" if had_nl else ""
        print(f"line {count}: {line.rstrip()}" + marker)
输出
line 1: alpha\n
line 2: beta\n
line 3: gamma

Rust v1.99.1

v1.99.1
use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    // BufRead::read_line 保留 "\n";BufRead::lines 则会剥掉
    std::fs::write("demo.txt", "alpha\nbeta\ngamma").unwrap();
    let mut h = BufReader::new(File::open("demo.txt").unwrap());
    let mut line = String::new();
    let mut count = 0;
    loop {
        line.clear();
        let n = h.read_line(&mut line).unwrap();
        if n == 0 {
            break; // EOF
        }
        count += 1;
        let had_nl = line.ends_with('\n');
        print!("line {}: {}", count, line.trim_end_matches('\n'));
        if had_nl {
            print!("\\n");
        }
        println!();
    }
}
输出
line 1: alpha\n
line 2: beta\n
line 3: gamma

TypeScript v26.13.1

v26.13.1
// Node 没有像 fgets 那样的行迭代器;确定性的等价做法是按 "\n" 切分
import * as fs from "node:fs";
fs.writeFileSync("demo.txt", "alpha\nbeta\ngamma");
const content: string = fs.readFileSync("demo.txt", "utf8");
const lines: string[] = content.split("\n"); // 此处没有结尾 "\n",不会产生空尾巴段
lines.forEach((line: string, i: number) => {
    const hadNl: boolean = i < lines.length - 1;
    console.log(`line ${i + 1}: ${line}${hadNl ? "\\n" : ""}`);
});
输出
line 1: alpha\n
line 2: beta\n
line 3: gamma

语言差异说明

C:fgets 保留换行(含 \n),缓冲上限 length-1 防溢出——PHP 语义的原型。

C++:std::getline 剥掉换行,EOF/失败使循环条件为假。

C#:ReadLine 剥掉换行;Peek() 为 -1 说明到了无换行的末行。

Go:bufio.Reader.ReadString 保留分隔符;bufio.Scanner 也是行级但按 token 语义剥掉换行。

Java:readLine 剥掉换行;ready() 报告缓冲区是否还有数据。

JavaScript:无内置行迭代器(readline 是事件流);整读再 split 是确定性演示的等价写法。

PHP:fgets 含换行,想要净行用 FILE_IGNORE_NEW_LINES(file 条目)或 rtrim;length 参数截断到 length-1 字节。

Python:文件迭代器保留换行;str.rstrip() 常用于剥掉。

Rust:read_line 保留换行(读进 String 末尾带 \n);lines() 迭代器剥掉。

TypeScript:同 JavaScript。