dongshengheng1013 2011-03-31 03:17
浏览 18
已采纳

从DYNAMIC文本文件中提取_基本的PHP问题

I am trying to extract contents from a txt file. This file is dynamic because data keeps appending to it everytime the loop is executed. Inside this loop rests my logic for extracting contents from file, as follows...

$length = filesize($filename);  
fseek($fd,$previousLength);  
$contents = fread($fd,(($length - $previousLength)));  
$previousLength = $length;  

i.e, I AM trying to read only the data that got appended, in the last loop ... and not the data that was previously written. EXAMPLE... A txt adds ONE everytime a loop is run.. i.e consider

114134, 144, 1443, 1433 ... 
(n of these written every once in loop ) ... 

If I read n values , say

114134, 144 ... 

in the first loop ...

next time, I need to read only

1443, 1443 and NOT 114134, 144 ....

fread() fails miserably here ,and fseek doesn't help ( ref. my code above) ...

I DON"T KNOW WHY !! help needed asap ..

Thanks

  • 写回答

2条回答 默认 最新

  • donglinxi1467 2011-03-31 03:55
    关注

    If you have opened the file in append mode then the man page for fseek says:

    If you have opened the file in append (a or a+) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined.

    The following code has a few modifications. I had a few problems with the length - fread does require it, but i decided to use fgets to avoid it. This would stop on newline characters but has the handy feature of reading the entire remaining contents of the file otherwise. There may be a better way of doing this, but this does work.

    <?php
    $filename = 'loopFile.txt';
    $previousLength = 0;
    $n = 0;
    
    $fw = fopen($filename, 'a+');
    $fr = fopen($filename, 'r');
    
    for ($i=0; $i < 15; $i++)
    {
       // Put a random number of numbers into the file.
       $numberOfNumbers = rand(0, 5);
    
       for ($writeCount = 0; $writeCount < $numberOfNumbers; $writeCount++)
       {
          fwrite($fw, $i . '_' . $n++ . ', ');
       }
    
       fseek($fr, $previousLength);  
       $contents = fgets($fr);
    
       if (!empty($contents))
       {
          echo 'On iteration: ' . $i . ' read: ' . $contents . "
    ";
       }
       else
       {
          echo 'On iteration: ' . $i . ' no new data appended to file.' . "
    ";
       }
    
       $previousLength += strlen($contents);  
    }
    
    fclose($fw);
    fclose($fr);
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集