douqin0676 2015-03-12 16:33
浏览 130

php:fwrite在fread之前保存,即使它在之后?

This is a tough one to explain in php. I've got a system that read a file, breaks the data by lines (" ") and then looks through the lines and comes up with a new data without one line marked by a $n variable. Then it writes.

Here's the problem: Its like fwrite is going first (when its last), then fread (which is first), then fwrite (which is last).

If I have a file with 31 lines, the fread will read the file as if it has 30 lines already with the proper line taken out. Then it will take out the proper line again, so I'll end up with a 29 line file. BUT if I remove the fread, the 31 line file loads properly. If I don't have a line removed, then it will keep all 31 lines.

I've simplified the code as much as I could. I've even added sleep(10) to hopefully delay fwrite until fread has read.

When I output a different file that works just fine as its supposed to, but if I try to take that output file and rename it to the original file, I still get the same problem. I've also used file_get_contents with file_put_contents with the same results.

Thanks for any help. Maybe you guys can tell me where I'm going wrong. Here's the code:

$handle = fopen($filename, 'r'); 
$Data = fread($handle, filesize($filename));
fclose($handle);

$pieces = explode("
", $Data);

// $n = the line to delete

$info = '';
for($i = 0 ; $i < sizeof($pieces) ; $i++){
    if($_REQUEST['n'] == $i && $pieces[$i] != ''){
        $info .= $pieces[$i]."
";
    }
}

// $filename never changes 
// $info is $Data without the specific $n line
$fp = fopen($filename, 'w+');
fwrite($fp, $info);
fclose($fp);
  • 写回答

1条回答 默认 最新

  • dtlzdofl66441 2015-03-26 17:40
    关注

    As it turns out, this was the result of a PHP 5.3.3 error. After upgrading to PHP 5.6 or so its no longer an issue.

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘