文件读取失败 . 请看是什么原因 .

yangsi_php yangsi_php 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
学习fseek函数之后 . 自己写了一个读文件尾部几行类似 linux tail 的功能 . 运行之后出现问题 .
ftell函数返回1 , 然后使用fread去读取却读取不到内容,
但是再次重新调用 fseek($handle,1) 之后,使用fread就能读取到内容了 .
是我哪里弄错了吗?

php代码如下

<?php
$demo = 'demo.txt';
$handle = fopen($demo, 'r');
$readLines = 4; $pos = -1; $data = array();
while ($readLines){
$curChar = '';
while ($curChar != "\n"){
$ftell = ftell($handle);
fseek($handle, $pos,SEEK_END);
$curChar = fgetc($handle);
$pos--;
if(!($ftell-1)) break;
}
$readLines--;
}
//指针==1 但是读不到内容
echo '#'.$curPointer = ftell($handle).'#';
var_dump(fread($handle,4096));
echo '<br />';

//调用fseek重置指针之后 可以获取到内容
fseek($handle, $curPointer);
echo '#'.ftell($handle).'#';
var_dump(fread($handle,4096));



文本文件如下

1
2
3
4


--------------------------------------------------------------------------------------
改了一下,使用fgetc读取当前字符,前面的读取到的是ascii 0,后面的读取到的是ascii 13


<?php
$demo = 'demo.txt';
$handle = fopen($demo, 'r');
$readLines = 4; $pos = -1; $data = array();
while ($readLines){
$curChar = '';
while ($curChar != "\n"){
$ftell = ftell($handle);
fseek($handle, $pos,SEEK_END);
$curChar = fgetc($handle);
$pos--;
if(!($ftell-1)) break;
}
$readLines--;
}
//指针==1 但是读不到内容
echo '#'.$curPointer = ftell($handle).'#';
var_dump(ord(fgetc($handle)));
//var_dump(fread($handle,4096));
echo '<br />';

//调用fseek重置指针之后 可以获取到内容
fseek($handle, $curPointer);
echo '#'.ftell($handle).'#';
//var_dump(fread($handle,4096));
var_dump(ord(fgetc($handle)));


结果是

#1#int(0)
#1#int(13)



确定是这里的问题(遇到空字符fread被截断了) ,但是ftell返回的为什么是1 . 是我写的有问题 还是这里是一个bug?
...全文

相关推荐

评论 4
收藏 已收藏
分享
返回顶部
yangsi_php
基础编程 21,889 成员 140,329 内容