PHP 文件
核对 fopen() 八种打开模式(r/r+/w/w+/a/a+/x/x+)、打开失败返回 false 处理、fclose() 资源释放、feof() 末尾检测,以及 fgets() 逐行与 fgetc() 逐字节读取实测。
学完这一章,你能够
- 核对 fopen() 八种打开模式(r/r+/w/w+/a/a+/x/x+)、打开失败返回 false 处理、fclose() 资源释放、feof() 末尾检测,以及 fgets() 逐行与 fgetc() 逐字节读取实测。
打开文件、模式选择与关闭文件
PHP 通过 `fopen($filename, $mode)` 打开本地文件并返回文件流句柄,第一参数为文件路径,第二参数规定读写与截断策略(涵盖 `r`、`r+`、`w`、`w+`、`a`、`a+`、`x`、`x+` 八种基础模式,详见下表)。若文件不存在或权限不足导致打开失败,`fopen()` 返回 `false`,典型写法会立即检查返回值(如 `or exit("Unable to open file!")` 或抛出异常)。
文件操作完毕后应调用 `fclose($file)` 及时刷新缓冲并释放操作系统文件描述符。本站 PHP 8.4.27 在临时目录实测全部 8 种模式:`w` 写入 `"Hello"` 且 `fclose()` 返回 `true`、`a` 追加后读得 `"Hello World"`、`r+` 从开头覆写前 5 字节得 `"PHP84 World"`、`w+` 清空重写得 `"Reset"`、`a+` 追加得 `"Reset+Tail"`,而独占新建模式 `x`/`x+` 在文件已存在时均准确返回 `false`。
EOF 检测、逐行 fgets() 与逐字符 fgetc() 读取
`feof($file)` 用于判断文件指针是否到达文件末尾(End Of File),常用于遍历长度未知的文件流。需注意在只写模式 `w`、`a`、`x` 下不能读取已打开的文件(本站实测对 `w` 模式句柄调用 `fread()` 无法读出数据,但底层内容已成功写入磁盘)。
`fgets($file)` 每次读取一行并将文件指针推进到下一行。工程上推荐写作 `while (($line = fgets($fp)) !== false)` 以避免末尾多循环一次,读完后 `feof($fp)` 为 `true`。本站实测读取三行 UTF-8 文本精准得到 3 条记录且结束时 `feof() === true`。
`fgetc($file)` 每次从流中读取单个字节字符并推进指针(注意对多字节 UTF-8 文本按字节拆分,更适合单字节/ASCII 解析)。本站实测对 `"PHP84\nOK"` 逐字节循环读取共 `8` 次、完整还原原文且 `feof() === true`。更多目录与文件 API 可参阅文末 PHP Filesystem 官方手册。
fopen() 文件打开模式对照表
| 模式 | 读写能力与文件指针行为 |
|---|---|
| r | 只读;文件指针位于开头,文件不存在时失败返回 false |
| r+ | 读/写;文件指针位于开头,从头覆写而不清空剩余内容 |
| w | 只写;打开并清空原内容,若文件不存在则创建新文件 |
| w+ | 读/写;打开并清空原内容,若文件不存在则创建新文件 |
| a | 追加只写;指针置于末尾保留原内容,不存在则创建 |
| a+ | 读/追加;写操作总追加到文件末尾,保留原有内容 |
| x | 独占创建只写;文件已存在时返回 false 并产生警告 |
| x+ | 独占创建读/写;文件已存在时返回 false 并产生警告 |
运行 fopen 八模式生命周期、fgets 逐行、fgetc 逐字节与错误分支实验
<?php
declare(strict_types=1);
$tmpDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'php_file_lab_' . bin2hex(random_bytes(6));
mkdir($tmpDir, 0777, true);
$cleanup = static function (string $dir): void {
if (!is_dir($dir)) {
return;
}
foreach (scandir($dir) ?: [] as $item) {
if ($item === '.' || $item === '..') {
continue;
}
@unlink($dir . DIRECTORY_SEPARATOR . $item);
}
@rmdir($dir);
};
$cases = [];
try {
// Case 1: All 8 fopen() modes (r, r+, w, w+, a, a+, x, x+) and fclose()
$fMain = $tmpDir . '/main.txt';
$fpW = fopen($fMain, 'w');
fwrite($fpW, 'Hello');
$closedW = fclose($fpW);
$fpA = fopen($fMain, 'a');
fwrite($fpA, ' World');
fclose($fpA);
$fpR = fopen($fMain, 'r');
$readAfterA = fread($fpR, 100);
fclose($fpR);
$fpRPlus = fopen($fMain, 'r+');
fwrite($fpRPlus, 'PHP84');
rewind($fpRPlus);
$readAfterRPlus = fread($fpRPlus, 100);
fclose($fpRPlus);
$fpWPlus = fopen($fMain, 'w+');
fwrite($fpWPlus, 'Reset');
rewind($fpWPlus);
$readAfterWPlus = fread($fpWPlus, 100);
fclose($fpWPlus);
$fpAPlus = fopen($fMain, 'a+');
fwrite($fpAPlus, '+Tail');
rewind($fpAPlus);
$readAfterAPlus = fread($fpAPlus, 100);
fclose($fpAPlus);
$fExcl = $tmpDir . '/exclusive.txt';
$fpX = fopen($fExcl, 'x');
fwrite($fpX, 'NewOnly');
fclose($fpX);
$secondXFailed = (@fopen($fExcl, 'x') === false);
$fExclPlus = $tmpDir . '/exclusive_plus.txt';
$fpXPlus = fopen($fExclPlus, 'x+');
fwrite($fpXPlus, 'RWNew');
rewind($fpXPlus);
$readXPlus = fread($fpXPlus, 100);
fclose($fpXPlus);
$secondXPlusFailed = (@fopen($fExclPlus, 'x+') === false);
$actual1 = [
'closed_w' => $closedW,
'after_w_and_a' => $readAfterA,
'after_r_plus_overwrite' => $readAfterRPlus,
'after_w_plus_truncate' => $readAfterWPlus,
'after_a_plus_append' => $readAfterAPlus,
'x_rejects_existing' => $secondXFailed,
'x_plus_read' => $readXPlus,
'x_plus_rejects_existing' => $secondXPlusFailed,
];
$expected1 = [
'closed_w' => true,
'after_w_and_a' => 'Hello World',
'after_r_plus_overwrite' => 'PHP84 World',
'after_w_plus_truncate' => 'Reset',
'after_a_plus_append' => 'Reset+Tail',
'x_rejects_existing' => true,
'x_plus_read' => 'RWNew',
'x_plus_rejects_existing' => true,
];
$cases[] = [
'name' => 'fopen_modes_rwax_lifecycle',
'passed' => $actual1 === $expected1,
'expected' => $expected1,
'actual' => $actual1,
];
// Case 2: Line-by-line reading with fgets() and feof()
$fLines = $tmpDir . '/welcome.txt';
file_put_contents($fLines, "第一行:欢迎\n第二行:PHP 文件处理\n第三行:结束");
$fp = fopen($fLines, 'r');
$lines = [];
while (($line = fgets($fp)) !== false) {
$lines[] = rtrim($line, "\r\n");
}
$atEof = feof($fp);
fclose($fp);
$actual2 = [
'line_count' => count($lines),
'lines' => $lines,
'eof_reached' => $atEof,
];
$expected2 = [
'line_count' => 3,
'lines' => ['第一行:欢迎', '第二行:PHP 文件处理', '第三行:结束'],
'eof_reached' => true,
];
$cases[] = [
'name' => 'fgets_line_by_line_eof',
'passed' => $actual2 === $expected2,
'expected' => $expected2,
'actual' => $actual2,
];
// Case 3: Character-by-character reading with fgetc() and feof()
$fChars = $tmpDir . '/chars.txt';
file_put_contents($fChars, "PHP84\nOK");
$fpC = fopen($fChars, 'r');
$chars = [];
while (($ch = fgetc($fpC)) !== false) {
$chars[] = $ch;
}
$eofC = feof($fpC);
fclose($fpC);
$actual3 = [
'char_count' => count($chars),
'reconstructed' => implode('', $chars),
'eof_reached' => $eofC,
];
$expected3 = [
'char_count' => 8,
'reconstructed' => "PHP84\nOK",
'eof_reached' => true,
];
$cases[] = [
'name' => 'fgetc_char_by_char_eof',
'passed' => $actual3 === $expected3,
'expected' => $expected3,
'actual' => $actual3,
];
// Case 4: Missing file returns false from fopen() and write-only mode ('w') cannot be read
$missingHandle = @fopen($tmpDir . '/missing.txt', 'r');
$fWriteOnly = $tmpDir . '/writeonly.txt';
$fpWO = fopen($fWriteOnly, 'w');
fwrite($fpWO, 'secret');
rewind($fpWO);
$readOnWriteOnly = @fread($fpWO, 10);
fclose($fpWO);
$actual4 = [
'missing_returns_false' => $missingHandle === false,
'read_on_w_mode_empty_or_false' => ($readOnWriteOnly === false || $readOnWriteOnly === ''),
'actual_written_via_file_get_contents' => file_get_contents($fWriteOnly),
];
$expected4 = [
'missing_returns_false' => true,
'read_on_w_mode_empty_or_false' => true,
'actual_written_via_file_get_contents' => 'secret',
];
$cases[] = [
'name' => 'fopen_missing_file_false_and_write_only_read',
'passed' => $actual4 === $expected4,
'expected' => $expected4,
'actual' => $actual4,
];
} finally {
$cleanup($tmpDir);
}
echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
- 核对 r/r+/w/w+/a/a+/x/x+ 八种模式实测结果、3 行文本 fgets+feof 读取、8 字节 fgetc 还原及不存在文件返回 false 行为。
所需环境:Windows x64、PHP 8.4 本地 CLI 环境。
当前源码 SHA256:48aaeca831f481218c5cc134b8255f6b5b93dc9797851b8a91105adefbd9fb88
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、PHP 8.4 本地 CLI 环境。
ZIP SHA256:9e8e76bbad1da59511b70203e894e74dcbd3d9fe25ceb48669a91944c05f0db9
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在打开不存在的文件和打开已存在的文件两种情况下,w 模式与 x 模式的行为有何核心差异?
展开参考解答
文件不存在时两者都会新建文件;但文件已存在时,w 模式会清空原内容继续写入,而 x 模式会直接失败返回 false 并报错,适合防止意外覆盖已有文件。