php - 打开,恐惧和蜂拥而至

标签 php file fopen

我需要锁定文件、读取数据、写入文件然后关闭它。我遇到的问题是我正在尝试为 fopen 找到正确的模式。

使用 'a+' - 始终附加数据,使用 'w+' 在打开时截断所有数据,使用 'x+' - 无法锁定文件。

这是我的代码:

$fh_task = fopen($task_file, 'w+');
flock($fh_task, LOCK_EX) or die('Cant lock '.$task_file);
$opt_line = '';
while(!feof($fh_task)){
  $opt_line .= fread($fh_task, 4096);
}
$options = unserialize($opt_line);
$options['procceed']++;
rewind($fh_task);
fwrite($fh_task, serialize($options));
flock($fh_task, LOCK_UN);
fclose($fh_task);

最佳答案

您需要 'r+'(如果您使用的是较新版本的 PHP,则需要 c+)。 r+ 不会截断(c+ 也不会),但仍然允许您编写。

这是我上次使用这些函数时的摘录:

        /* 
          if file exists, open in read+ plus mode so we can try to lock it 
          -- opening in w+ would truncate the file *before* we could get a lock!
        */

        if(version_compare(PHP_VERSION, '5.2.6') >= 0) {
            $mode = 'c+';
        } else {
            //'c+' would be the ideal $mode to use, but that's only 
            //available in PHP >=5.2.6

            $mode = file_exists($file) ? 'r+' : 'w+';
            //there's a small chance of a race condition here
            // -- two processes could end up opening the file with 'w+'
        }

        //open file
        if($handle = @fopen($file, $mode)) {
            //get write lock
            flock($handle,LOCK_EX);
            //write data
            fwrite($handle, $myData);
            //truncate all data in file following the data we just wrote 
            ftruncate($handle,ftell($handle));
            //release write lock -- fclose does this automatically
            //but only in PHP <= 5.3.2
            flock($handle,LOCK_UN);
            //close file
            fclose($handle);
        }

关于php - 打开,恐惧和蜂拥而至,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5682616/

相关文章:

c - Linux 上的 feof() 在结束行晚一行返回 true

c - 从c中的文本文件中读取列的算法

php - 如何使用 Codeigniter 构建动态网站

php - 浏览器要求我下载 php 文件

linux - 如何在 Linux 上查找哪些进程已写入文件

java - 标点符号和 .next() 方法

无法以附加或写入模式打开文件

php - Jquery ajax 调用 : can't use numbers

php - 从 HTML 片段的字符串创建 DOMNode

php - 更改 Javascript 变量而不刷新