dsa122870 2013-10-08 12:56
浏览 60
已采纳

如何重写同一个文件

Currently I'm doing it like this:

$f = fopen('test', 'w');
fwrite($f, 'Hi');
fclose($f);

But I have a loop that does some expensive stuff (with files), and I'd like to avoid opening and closing the file handle every time I want to overwrite "test"

It should be something like this:

$f = fopen('test', 'w');

$i = 0;
while($ < 50000){

  $i++;
  foverwrite($f, 'i = ' . $i);

  sleep(5); // just a example

}

fclose($f);

Is this possible?

This script runs in the background in CLI mode and I'm reading the test file from the web with ajax like every 2 seconds. Basically I'm trying to display a progress bar lol

  • 写回答

5条回答 默认 最新

  • dtvhqlc57127 2013-10-19 09:35
    关注

    To go along with your example, you could implement your foverwrite() function using frewind() like this:

    function foverwrite($handle,$content)
      {
      frewind($handle);
      return fwrite($handle,$content);
      }
    

    This function will return fwrite()'s return value, so it can readily replace fwrite() where needed. Also, in case of opening the file in append mode (a or a+) it will just append contens, as frewind() will make no difference.

    However, concerning the purpose of your script, which clearly is interprocess communication, you should take a look at more efficient techniques, like shared memory.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?