zoukankan      html  css  js  c++  java
  • 用递归遍历文件夹和N层的子文件夹

    /**
     * 遍历文件夹
     */
    function Tree($space='',$dir="./")
    {
        //建立dir对象
        $d = dir($dir);
        //得到子级文件及文件夹总数
        $sonSum=count(scandir($dir));
        while (false !== ($entry = $d->read()))
        {
            $sonSum--;
            //判断是否为最后一个,输出对应的树杈
            $list=$sonSum?"├":"└";
            //去掉两个默认的目录
            if($entry=='..' or $entry=='.')
            continue;
     
            //页面是utf-8的,系统是winXP,所以需要将文件名进行转码
            echo $space.$list.iconv('gb2312','utf-8',$entry)."
    \n";
            //输出当前目录/文件
            $currentPath=$d->path.'/'.$entry;
            //如果是目录则遍历这个目录
            if(is_dir(realpath($currentPath)))
                //调用函数本身
                Tree($space.($sonSum?'│':'').' ',$currentPath);
        }
        $d->close();
    }
    Tree();

    当然上面的代码只是生成一个类似ms-dos中的tree /all命令生成的树状目录结构。
    去掉显示树杈的部分就可以投入生产了。
    去掉显示树杈代码后如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    /**
     * 遍历文件夹
     */
    function Tree($dir="./")
    {
        $d = dir($dir);
        while (false !== ($entry = $d->read()))
        {
            if($entry=='..' or $entry=='.')
            continue;
     
            echo $space.$list.iconv('gb2312','utf-8',$entry)."
    \n";
            $currentPath=$d->path.'/'.$entry;
            if(is_dir(realpath($currentPath)))
                Tree($currentPath);
        }
        $d->close();
    }
    Tree();

    递归遍历文件夹,并计算文件夹大小的代码是:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    function dirsize($dir) {
     @$dh = opendir($dir);
     $size = 0;
     while ($file = @readdir($dh)) {
      if ($file != "." and $file != "..") {
       $path = $dir."/".$file;
       if (is_dir($path)) {
        $size += dirsize($path);
       } elseif (is_file($path)) {
        $size += filesize($path);
       }
      }
     }
     @closedir($dh);
     return $size;
    }

  • 相关阅读:
    笔记:Maven 聚合和继承
    笔记:Maven 仓库和插件配置本机私服
    笔记:Maven 插件配置
    笔记:Maven 仓库及配置详解
    笔记:Maven 插件及配置详解
    笔记:Maven 依赖及配置详解
    笔记:Maven 项目基本配置
    【问题解决方案】Mathtype中丢失Mplugin.dll的问题
    【学习总结】Python-3-字符串函数-strip()方法
    【学习总结】Python-3-字符串函数split()的妙用
  • 原文地址:https://www.cnblogs.com/see7di/p/2239877.html
Copyright © 2011-2022 走看看