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

yangsi_php 2017-04-01 07:27:02
学习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?
...全文
1097 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xuzuning 2017-04-01
  • 打赏
  • 举报
回复
嗯,与最后一行的结尾是否有换行有关
其实最后一行的换行符应该是不被统计的
$handle = fopen($demo, 'r');
$readLines = 2;
fseek($handle, 0, SEEK_END); //定位到之后一个字符
while($readLines) {
if(fseek($handle, -2, SEEK_CUR) < 0) {
fseek($handle, 0, SEEK_SET);
break;
}
if(fgetc($handle) == "\n") $readLines--;
}
echo fread($handle,4096);
yangsi_php 2017-04-01
  • 打赏
  • 举报
回复
引用 2 楼 yangsi_php 的回复:
[quote=引用 1 楼 xuzuning 的回复:]
echo '#'.$curPointer = ftell($handle).'#';
var_dump(fread($handle,4096));
得:
#3#string(9) "2
3
4
"
这不算输出吗?


我这边没有输出 . 必须要先调用fssek($curPointer) .然后才有内容 .
难道是文本文件的问题?[/quote]

文本文件是这样的
yangsi_php 2017-04-01
  • 打赏
  • 举报
回复
引用 1 楼 xuzuning 的回复:
echo '#'.$curPointer = ftell($handle).'#'; var_dump(fread($handle,4096)); 得: #3#string(9) "2 3 4 " 这不算输出吗?
我这边没有输出 . 必须要先调用fssek($curPointer) .然后才有内容 . 难道是文本文件的问题?
xuzuning 2017-04-01
  • 打赏
  • 举报
回复
echo '#'.$curPointer = ftell($handle).'#'; var_dump(fread($handle,4096)); 得: #3#string(9) "2 3 4 " 这不算输出吗?

21,894

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧