如何确保在下次操作之前已关闭文件句柄


How to make sure a file handle has been closed before next operation?

这是我到目前为止的代码,我想知道它是否正确?

$handle = fopen($file, 'w') or die("can't open file");
$closed = fclose($handle);
while($closed){
    DOAWESOMETHINGS(); // btw I only want to have this run once for each handle
    $closed = false;
}

非常感谢!

可以使用下面的语句检查句柄是否已关闭

if(!is_resource($handle)){
   //Handle closed
}else{
   //Handle still open
}

因此,如果您需要在运行下一个函数之前确保fclose已经工作,您可以使用以下循环:

while(is_resource($handle)){
   //Handle still open
   fclose($handle);
}
do_awesome_things();

注意:当你需要时,你也应该使用break;来结束while循环。在这个例子中,直到句柄关闭,循环才会结束。