php高效读取和写入
/** * 删除非空目录里面所有文件和子目录 * @param string $dir * @return boolean */ function fn_rmdir($dir) { //先删除目录下的文件: $dh = opendir($dir); while ($file = readdir($dh)) { if ($file != "." && $file != "..") { $fullpath = $dir . "/" . $file; if (is_dir($fullpath)) { fn_rmdir($fullpath); } else { unlink($fullpath); } } } closedir($dh); //删除当前文件夹: if (rmdir($dir)) { return true; } else { return false; } } /** * PHP高效读取文件 * @param string $filepath * @return string */ function fn_tail($filepath) { if (file_exists($filepath)) { $fp = fopen($filepath, "r"); $str = ""; $buffer = 1024; //每次读取 1024 字节 while (!feof($fp)) {//循环读取,直至读取完整个文件 $str .= fread($fp, $buffer); } return $str; } } /** * PHP高效写入文件(支持并发) * @param string $filepath * @param string $content */ function fn_write($filepath, $content) { if ($fp = fopen($filepath, 'a')) { $startTime = microtime(); // 对文件进行加锁时,设置一个超时时间为1ms,如果这里时间内没有获得锁,就反复获得,直接获得到对文件操作权为止,当然。如果超时限制已到,就必需马上退出,让出锁让其它进程来进行操作。 do { $canWrite = flock($fp, LOCK_EX); if (!$canWrite) { usleep(round(rand(0, 100) * 1000)); } } while ((!$canWrite) && ((microtime() - $startTime) < 1000)); if ($canWrite) { fwrite($fp, $content); } fclose($fp); } }
转载于https://www.cnblogs.com/sochishun/p/7375328.html
使用php生成器yield可以看这个https://www.jb51.net/article/160564.htm
踩过这个坑,还有下一个坑等着你,这一路就是给自己填坑,坑填多了,也就习惯了,直到这一路平坦了,也就无怨无悔了。