PHP fseek 函数
最后修改于 2025 年 4 月 3 日
PHP fseek
函数用于设置文件指针的文件位置指示器。它允许通过移动指针来随机访问文件内容。
基本定义
fseek
函数将文件指针移动到指定位置。它接受三个参数:文件指针、偏移量和可选的 whence。
语法:fseek(resource $stream, int $offset, int $whence = SEEK_SET): int
。成功返回 0,失败返回 -1。适用于以二进制模式打开的文件。
基本的 fseek 示例
这显示了 fseek
移动文件指针的最简单用法。
basic_fseek.php
<?php declare(strict_types=1); $file = fopen('data.txt', 'rb'); if ($file === false) { die("Failed to open file"); } fseek($file, 10); echo fread($file, 20); fclose($file);
这会将指针移动到位置 10 并读取 20 字节。默认的 whence 参数是 SEEK_SET,表示偏移量是相对于文件开头计算的。
从当前位置搜索
使用 SEEK_CUR 将指针移动到相对于其当前位置。
fseek_current.php
<?php declare(strict_types=1); $file = fopen('data.txt', 'rb'); if ($file === false) { die("Failed to open file"); } fseek($file, 10, SEEK_SET); // Move to position 10 fseek($file, 5, SEEK_CUR); // Move 5 more bytes echo fread($file, 15); fclose($file);
这首先移动到位置 10,然后向前移动 5 个字节。最终位置是从文件开头算起的第 15 个字节。
从文件末尾搜索
使用 SEEK_END 将指针移动到相对于文件末尾。
fseek_end.php
<?php declare(strict_types=1); $file = fopen('data.txt', 'rb'); if ($file === false) { die("Failed to open file"); } fseek($file, -10, SEEK_END); // 10 bytes from end echo fread($file, 10); fclose($file);
这会将指针定位在文件末尾之前 10 个字节。在 SEEK_END 中经常使用负偏移量来读取文件的末尾。
检查文件位置
结合 fseek
和 ftell
来验证位置。
fseek_ftell.php
<?php declare(strict_types=1); $file = fopen('data.txt', 'rb'); if ($file === false) { die("Failed to open file"); } fseek($file, 25); echo "Position: " . ftell($file) . "\n"; fseek($file, -5, SEEK_CUR); echo "New position: " . ftell($file) . "\n"; fclose($file);
这显示了在定位之前和之后当前位置。ftell
返回从文件开头测量的当前位置(以字节为单位)。
错误处理
检查 fseek
的返回值以进行错误处理。
fseek_error.php
<?php declare(strict_types=1); $file = fopen('data.txt', 'rb'); if ($file === false) { die("Failed to open file"); } $result = fseek($file, 1000000); if ($result === -1) { echo "Seek failed - position may be beyond EOF\n"; } else { echo "Seek successful\n"; } fclose($file);
这尝试定位到可能的文件大小之外。函数在失败时返回 -1。请注意,定位到 EOF 之外在 PHP 中并不总是错误。
最佳实践
- 二进制模式:始终以二进制模式打开文件以进行可靠的定位。
- 错误检查:验证 fopen 和 fseek 的返回值。
- 位置验证:检查位置是否不超过文件大小。
- 资源清理:始终使用 fclose 关闭文件。
- 大文件:在非常大的文件(> 2GB)上使用时要小心。
来源
本教程通过实际示例涵盖了 PHP fseek
函数,展示了其在不同场景下的用法。
作者
列出 所有 PHP 文件系统函数。