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

瘦欲@ 提交于 2019-12-23 20:52:51

问题


This is the code I have so far, I wonder if it's correct?

$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;
}

Thank you so much!


回答1:


You can check whether the handle has been closed or not using this statement

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

Therefore, if you need to ensure that fclose has worked before running the next function, you can use this loop:

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

Note: You should also use break; to end while loops when you need to. In this instance the loop will not end until the handle is closed.



来源:https://stackoverflow.com/questions/5650361/how-to-make-sure-a-file-handle-has-been-closed-before-next-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!