file
file(string $filename, int $flags = 0, ?resource $context = null): array|false
整文件读成行数组(默认每行保留换行,FILE_IGNORE_NEW_LINES 剥掉)——与 file_get_contents 的「单串」对照:要逐行处理选 file(),要整体文本选 file_get_contents。
C C23
C23
#include <stdio.h>
#include <string.h>
int main(void) {
// C 没有整读成行数组的函数:fopen + fgets 循环即手搓版 file()
FILE *w = fopen("demo.txt", "w");
fputs("alpha\nbeta\ngamma", w);
fclose(w);
FILE *h = fopen("demo.txt", "r");
char lines[4][16];
int count = 0;
while (count < 4 && fgets(lines[count], sizeof lines[count], h)) {
lines[count][strcspn(lines[count], "\n")] = '\0'; // 剥掉 "\n",同 FILE_IGNORE_NEW_LINES
count++;
}
fclose(h);
printf("count: %d\n", count);
printf("first: %s\n", lines[0]);
printf("last: %s\n", lines[count - 1]);
return 0;
}
输出
count: 3 first: alpha last: gamma
C++ C++26
C++26
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main() {
// file() 的形态:getline 循环收进 vector
{
std::ofstream w("demo.txt");
w << "alpha\nbeta\ngamma";
}
std::ifstream h("demo.txt");
std::vector<std::string> lines;
std::string line;
while (std::getline(h, line)) { // 剥掉 "\n",同 FILE_IGNORE_NEW_LINES
lines.push_back(line);
}
std::cout << "count: " << lines.size() << "\n";
std::cout << "first: " << lines.front() << "\n";
std::cout << "last: " << lines.back() << "\n";
}
输出
count: 3 first: alpha last: gamma
C# v11.0.100
v11.0.100
// File.ReadAllLines 是直接等价物(内置剥换行)
using System.IO;
File.WriteAllText("demo.txt", "alpha\nbeta\ngamma");
string[] lines = File.ReadAllLines("demo.txt"); // 剥换行,同 FILE_IGNORE_NEW_LINES
Console.WriteLine("count: " + lines.Length);
Console.WriteLine("first: " + lines[0]);
Console.WriteLine("last: " + lines[lines.Length - 1]);
输出
count: 3 first: alpha last: gamma
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"os"
"strings"
)
func main() {
// Go:整读再 Split——file() 的形态
os.WriteFile("demo.txt", []byte("alpha\nbeta\ngamma"), 0644)
data, err := os.ReadFile("demo.txt")
if err != nil {
panic(err)
}
lines := strings.Split(string(data), "\n")
fmt.Printf("count: %d\n", len(lines))
fmt.Printf("first: %s\n", lines[0])
fmt.Printf("last: %s\n", lines[len(lines)-1])
}
输出
count: 3 first: alpha last: gamma
Java v27.0.1
v27.0.1
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
// Files.readAllLines 是直接等价物(内置剥换行)
Path p = Path.of("demo.txt");
Files.writeString(p, "alpha\nbeta\ngamma");
List<String> lines = Files.readAllLines(p); // 剥换行,同 FILE_IGNORE_NEW_LINES
System.out.println("count: " + lines.size());
System.out.println("first: " + lines.get(0));
System.out.println("last: " + lines.get(lines.size() - 1));
}
}
输出
count: 3 first: alpha last: gamma
JavaScript v26.13.1
v26.13.1
// Node:整读成串再 split——file() 的形态
const fs = require("node:fs");
fs.writeFileSync("demo.txt", "alpha\nbeta\ngamma");
const lines = fs.readFileSync("demo.txt", "utf8").split("\n"); // 此处无结尾换行
console.log("count:", lines.length);
console.log("first:", lines[0]);
console.log("last:", lines[lines.length - 1]);
输出
count: 3 first: alpha last: gamma
PHP v8.6.0
v8.6.0
// file() = file_get_contents() + 按行切开;FILE_IGNORE_NEW_LINES 剥掉 "\n"
file_put_contents("demo.txt", "alpha\nbeta\ngamma");
$lines = file("demo.txt", FILE_IGNORE_NEW_LINES);
echo "count: ", count($lines), "\n";
echo "first: ", $lines[0], "\n";
echo "last: ", $lines[2], "\n";
输出
count: 3 first: alpha last: gamma
Python v3.15.2
v3.15.2
# read_text() + splitlines()——splitlines() 剥换行,同 FILE_IGNORE_NEW_LINES
from pathlib import Path
Path("demo.txt").write_text("alpha\nbeta\ngamma")
lines = Path("demo.txt").read_text().splitlines()
print(f"count: {len(lines)}")
print(f"first: {lines[0]}")
print(f"last: {lines[-1]}")
输出
count: 3 first: alpha last: gamma
Rust v1.99.1
v1.99.1
use std::fs;
fn main() {
// read_to_string + lines()——lines() 剥掉 "\n",同 FILE_IGNORE_NEW_LINES
fs::write("demo.txt", "alpha\nbeta\ngamma").unwrap();
let text = fs::read_to_string("demo.txt").unwrap();
let lines: Vec<&str> = text.lines().collect();
println!("count: {}", lines.len());
println!("first: {}", lines[0]);
println!("last: {}", lines[lines.len() - 1]);
}
输出
count: 3 first: alpha last: gamma
TypeScript v26.13.1
v26.13.1
// Node:整读成串再 split——file() 的形态
import * as fs from "node:fs";
fs.writeFileSync("demo.txt", "alpha\nbeta\ngamma");
const lines: string[] = fs.readFileSync("demo.txt", "utf8").split("\n");
console.log("count:", lines.length);
console.log("first:", lines[0]);
console.log("last:", lines[lines.length - 1]);
输出
count: 3 first: alpha last: gamma
语言差异说明
C:无整读成行函数,fgets 循环收进二维数组即手搓版(strcspn 剥换行)。
C++:getline 循环进 std::vector<std::string>,无单行内建。
C#:File.ReadAllLines 直接等价。
Go:标准库只有 os.ReadFile 整读字节,strings.Split 按行切开——file() 是组合出来的。
Java:Files.readAllLines 直接等价。
JavaScript:readFileSync + split("\n") 组合;注意结尾有换行时 split 会产生空尾巴,需过滤。
PHP:默认每行保留换行;FILE_IGNORE_NEW_LINES 剥掉、FILE_SKIP_EMPTY_LINES 跳空行、非法 flags 自 PHP 8.3 抛 ValueError。
Python:splitlines() 直接等价且能识别多种行尾。
Rust:str::lines() 直接等价(按 \n 与 \r\n 切)。
TypeScript:同 JavaScript。