PHP ftell 函数
最后修改于 2025 年 4 月 3 日
PHP 的 ftell
函数返回打开文件中文件指针的当前位置。这对于随机文件访问操作至关重要。
基本定义
ftell
函数返回给定文件句柄中文件指针的当前位置。它以字节为单位测量从开始位置的位置。
语法:ftell(resource $stream): int|false
。 失败时返回位置为整数或 false。 适用于使用 fopen
打开的文件。
基本 ftell 示例
这展示了 ftell
的最简单用法,以获取指针位置。
basic_ftell.php
<?php declare(strict_types=1); $file = fopen('example.txt', 'r'); $position = ftell($file); echo "Initial position: $position"; // Outputs: Initial position: 0 fclose($file);
这表明当文件首次打开时,指针从位置 0 开始。该位置以字节为单位从文件的开头测量。
读取数据之后
ftell
显示了读取如何使文件指针向前移动。
after_read.php
<?php declare(strict_types=1); $file = fopen('example.txt', 'r'); fread($file, 10); // Read 10 bytes $position = ftell($file); echo "Position after read: $position"; // Outputs position 10 fclose($file);
读取 10 个字节后,ftell
返回 10。指针会在读/写操作期间自动移动。
使用 fseek
ftell
可以验证由 fseek
设置的位置。
with_fseek.php
<?php declare(strict_types=1); $file = fopen('example.txt', 'r'); fseek($file, 25); $position = ftell($file); echo "Position after seek: $position"; // Outputs position 25 fclose($file);
这演示了 ftell
如何确认手动指针定位。位置与 fseek
的 25 字节偏移量匹配。
写入模式
在写入模式下,ftell
显示当前写入位置。
writing_mode.php
<?php declare(strict_types=1); $file = fopen('output.txt', 'w'); fwrite($file, 'Hello'); $position = ftell($file); echo "Position after write: $position"; // Outputs position 5 fclose($file);
写入 "Hello" (5 个字节) 后,ftell
返回 5。指针移动到已写入数据的末尾。
追加模式
在追加模式下,ftell
始终显示结束位置。
append_mode.php
<?php declare(strict_types=1); $file = fopen('log.txt', 'a'); $position = ftell($file); echo "Initial append position: $position"; // Shows file size fwrite($file, "New entry\n"); $position = ftell($file); echo "New append position: $position"; // Shows new end position fclose($file);
追加模式从文件的末尾开始。ftell
在每次写入操作后反映当前的结束位置。
错误处理
ftell
在失败时返回 false,应该进行检查。
error_handling.php
<?php declare(strict_types=1); $file = fopen('nonexistent.txt', 'r'); if ($file === false) { die("File open failed"); } $position = ftell($file); if ($position === false) { die("ftell failed"); } echo "Position: $position"; fclose($file);
这显示了适当的错误处理。始终检查 ftell
是否返回 false,这表示错误情况。
最佳实践
- 错误检查: 始终验证 ftell 不返回 false。
- 二进制安全: 使用 'b' 模式以获得一致的位置。
- 大型文件: 在 64 位系统上适用于大于 2GB 的文件。
- 流: 适用于可搜索的网络流。
来源
本教程介绍了 PHP ftell
函数,并提供了实际示例,展示了在不同场景中跟踪文件指针位置。
作者
列出 所有 PHP 文件系统函数。