详谈PHP文件目录基础操作(6)
如果想要读取方式更灵活,就要配合fseek、rewind使用,它们可以移动文件指针到具体位置,fseek十分灵活,可以直接移到开头或末尾,或从当前位置往前或
如果想要读取方式更灵活,就要配合fseek、rewind使用,它们可以移动文件指针到具体位置,fseek十分灵活,可以直接移到开头或末尾,或从当前位置往前或后移动,读取想要的内容,ftell还可告知当前位置,比如:
复制代码 代码如下:
<?php
function readFun($filepath){
if(($handle = @fopen($filepath, 'r')) != false){
echo 'current position: '.ftell($handle).'<br>'; // 输出文件当前文件指针位置,以字节算,0表示开头
$str = fread($handle, 3); // 读取3个字节,同时指针自动后移3个字节
echo 'read content: '.$str.'<br>';
echo 'current position: '.ftell($handle).'<br>';
fseek($handle, 5, SEEK_CUR); // 将文件指针从当前位置后移5个字节
echo 'current position: '.ftell($handle).'<br>';
$str = fread($handle, 5);
echo 'read content: '.$str.'<br>';
echo 'current position: '.ftell($handle).'<br>';
rewind($handle); // 返回文件开头
echo 'current position: '.ftell($handle).'<br>';
fseek($handle, 0, SEEK_END); // 移到文件末尾
echo 'current position: '.ftell($handle).'<br>';
fclose($handle); // 关闭文件
}
}
比如我现在使用该方法读取一个写有从a到z的文本文件,看看效果:

以上就是php关于目录文件操作的全部内容了,也是个人的一份理解记录吧,希望对大家有所帮助
精彩图集
精彩文章






