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

问题描述

| 这是我到目前为止的代码,我想知道它是否正确?
$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();
注意:您还应在需要时使用ѭ3结束while循环。在这种情况下,直到句柄关闭,循环才会结束。