目录遍历( 递归方式和队列方式 )

目录遍历方式

主要函数:opendir(), readdir(), closedir()

  //递归函数实现遍历指定文件下的目录与文件数量  
    function total( $dirname, &$dirnum, &$filenum ){  
        $dir=opendir($dirname);  
        while($filename=readdir($dir)){  
            if('.' == $filename OR '..' == $filename)continue; 
            $newfile=$dirname."/".$filename;  
       //判断是否是目录 
            if(is_dir($newfile)){  
                //通过递归函数再遍历其子目录下的目录或文件  
                $dirnum++;  
                total($newfile,$dirnum,$filenum);  
            }else{  
                $filenum++;  
            }  
        }  
        closedir($dir);  
    }  
        
    $dirnum=0;  
    $filenum=0;  
    total('/var/www/learnlaravel/app/models',$dirnum,$filenum);  
    echo "目录总数:".$dirnum."\n";  
    echo "文件总数:".$filenum."\n";   //遍历指定文件目录与文件数量结束

 

队列方式遍历

主要函数:dir()[ 返回一个 Directory 类实例 ], 用到Directory类方法read()。

function  getfiles($path='.'){
    $queue=array($path);

    while (!empty($queue)) {
        $currentPath=array_shift($queue);
        $currentDir = dir($currentPath);
        while (false !== ($filePath = $currentDir->read())) {
           if( '.' == $filePath || '..' == $filePath ){
                   continue;
           }
           if(is_dir($currentPath.'/'.$filePath)){
                  array_push($queue, $currentPath.'/'.$filePath);
           }
           echo $currentPath.'/'.$filePath."\n";
        }
        $currentDir->close();
    }

}

getfiles('d:/software');

 

posted @ 2015-01-15 11:01  leezhxing  阅读(700)  评论(0编辑  收藏  举报