【问题标题】:How to lock a file, read content and overwrite (truncate) it如何锁定文件、读取内容并覆盖(截断)它
【发布时间】:2021-11-29 21:07:45
【问题描述】:

当我使用选项w+ 时,它会在读取文件之前截断文件。我想锁定多个脚本使用的文件,然后读取和覆盖,然后解锁。这是简化的代码。

$fp = fopen($file, "w+");
if(flock($fp, LOCK_EX)) {
    $content = fread($fp, $filesize);
    echo $content; // this is empty, must not be empty
    $job_queue = explode("\n", $content, LOCK_EX);
    $next_job = array_shift($job_queue);
    fwrite($fp, implode("\n", $job_queue));
    flock($fp, LOCK_UN);
} else {
    echo '<br>Error: cannot lock job queue file';
}
fclose($fp);

【问题讨论】:

    标签: php file


    【解决方案1】:
    r = read mode only
    r+ = read/write mode
    w = write mode only
    w+ = read/write mode, if the file already exists override it (empty it)
    

    改为 "r+" 并使用 PHP 的 ftruncate() 截断

    【讨论】:

    • 我刚做了这个,但你打败了我:D
    • 这样就可以了,对吧?
    • 没有。它不适用于 r+。需要做a+并截断为0
    • 查看文档中的示例 #1,它使用 r+
    • 它损坏了文件,我不明白为什么。
    【解决方案2】:

    为了解决这个问题,手动将截断添加到 0(文件开头)并将打开选项更改为 a+

    $fp = fopen($file, "a+");
    if(flock($fp, LOCK_EX)) {
        $content = fread($fp, $filesize);
        echo $content; // this is not empty now
        $job_queue = explode("\n", $content, LOCK_EX);
        $next_job = array_shift($job_queue);
        ftruncate($fp, 0);
        fwrite($fp, implode("\n", $job_queue));
        flock($fp, LOCK_UN);
    } else {
        echo '<br>Error: cannot lock job queue file';
    }
    fclose($fp);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 2012-08-08
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      • 2010-12-26
      相关资源
      最近更新 更多