【问题标题】:Changing fopen() mode midway through?中途改变 fopen() 模式?
【发布时间】:2011-01-18 20:17:42
【问题描述】:

我这段代码:

$file = fopen($path, 'r+');
flock($file, LOCK_EX);
// reading the file into an array and doing some stuff to it
for ($i=0; $i<count($array); $i++)
  {
  fwrite($file, $array[$i]);
  }
flock($file, LOCK_UN);
fclose($file);

基本上我想做的是:打开一个文件>锁定它>读取它>做一些事情>清除文件>写入文件>解锁它>关闭它。

问题是清算部分。我知道我可以用fopen($file, 'w+') 做到这一点,但是阅读将是一个问题。也许我可以以某种方式更改mode

任何帮助将不胜感激,保罗

【问题讨论】:

    标签: php file fopen


    【解决方案1】:

    如果您使用 fseek 将指针设置为 0,则可以像这样运行 ftruncate

    // reading the file into an array and doing some stuff to it
    
    //1
    fseek($handle,0); //Set the pointer to the first byte
    
    //2
    ftruncate($handle,filesize("yourfile.ext")); //from the first byte to the last truncate
    
    //3 - File should be empty and still in writing mode.
    
    for ($i=0; $i<count($array); $i++)
    {
        fwrite($file, $array[$i]);
    }
    

    使用ftruncate 请注意关于第二个参数的这些问题:

    【讨论】:

      【解决方案2】:
      fopen($file, 'r+')
      

      包括阅读和写作。前进吧,繁荣昌盛。

      r+ 说明: 开放阅读和写作;将文件指针放在文件的开头。

      w+ 描述: 开放阅读和写作;将文件指针放在文件的开头并将文件截断为零长度。如果文件不存在,请尝试创建它。

      来源:http://php.net/manual/en/function.fopen.php

      【讨论】:

      • 要么我不明白你的答案,要么你不明白我的问题。 r+ 好的,但在写入之前不会清除文件。 w+ 清空好用,读空文件有什么用?
      【解决方案3】:

      你可以有单独的锁空文件并调用flock($file, LOCK_EX);在该文件上并打开另一个文件进行写入。

      【讨论】:

      • 不需要第二个文件就可以做到这一点
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      相关资源
      最近更新 更多