[原创] Tips: 两种目录遍历的方法
来源:互联网 发布:js url encode 在线 编辑:程序博客网 时间:2024/06/05 15:18
目录的遍历是个老问题,主要用在目录遍历类操作,比如删除、统计磁盘占用等等情况。目录就是一个典型的树形结构,递归是最简单的方法了。
function ErgodicDirectory1($dir) {
$dp = opendir($dir);
while ($file = readdir($dp)) {
if ($file!='.' && $file!='..') {
$path = $dir ."/". $file;
if (is_dir($path)) {
echo "目录:" .$path. chr(10);
ErgodicDirectory1($path);
} else {
echo "文件:" .$path. chr(10);
}
}
}
closedir($dp);
}
$dp = opendir($dir);
while ($file = readdir($dp)) {
if ($file!='.' && $file!='..') {
$path = $dir ."/". $file;
if (is_dir($path)) {
echo "目录:" .$path. chr(10);
ErgodicDirectory1($path);
} else {
echo "文件:" .$path. chr(10);
}
}
}
closedir($dp);
}
利用一个栈来递归消除:
function ErgodicDirectory2($dir) {
$stack = array($dir);
while (!empty($stack)) {
$curr_dir = array_pop($stack);
if ($dp = opendir($curr_dir)) {
while (($file = readdir($dp))) {
if ($file!='.' && $file!='..') {
$curr_file = "$curr_dir/$file";
if (is_dir($curr_file)) {
echo "目录:". $curr_file . chr(10);
$stack[] = $curr_file;
} else {
echo "文件:". $curr_file . chr(10);
}
}
}
closedir($dp);
}
}
}
$stack = array($dir);
while (!empty($stack)) {
$curr_dir = array_pop($stack);
if ($dp = opendir($curr_dir)) {
while (($file = readdir($dp))) {
if ($file!='.' && $file!='..') {
$curr_file = "$curr_dir/$file";
if (is_dir($curr_file)) {
echo "目录:". $curr_file . chr(10);
$stack[] = $curr_file;
} else {
echo "文件:". $curr_file . chr(10);
}
}
}
closedir($dp);
}
}
}
- [原创] Tips: 两种目录遍历的方法
- [原创] Tips: 两种目录遍历的方法
- [原创] Tips: 两种目录遍历的方法
- 遍历目录的两种方法
- PHP中遍历目录的两种方法
- Python遍历目录文件的两种方法
- Java遍历文件目录的两种方法
- LINUX编程学习笔记(十三) 遍历目录的两种方法
- 目录遍历的方法
- 目录遍历的方法
- 由两种简单的遍历指定目录下文件的方法来看os模块中的一些方法
- 遍历map的两种方法
- 两种遍历Hashtable的方法
- J2ME:rms的两种遍历方法
- 遍历HashTable的两种方法
- 遍历map的两种方法
- java遍历文件夹的两种方法
- 两种遍历二维数组的方法
- 用Eclipse+MyEclipse开发struts的一个经典的实例
- 第一次
- Openlaszlo应用初始化性能优化过程
- oracle ORA-12560
- 新闻标题太长,截取字段,鼠标放上去显示全部
- [原创] Tips: 两种目录遍历的方法
- 在java中用JDBC连接SQL Server 2000 的经验分享
- 核心对象Kernel Objects
- error LNK2001错误
- 5-1 自定义Qt控件(Customizing Qt Widgets)
- Collection List Set Map 区别记忆
- window.location.reload()与IsPostBack的一些解释
- 千呼万唤始出来——InfoQ中文站
- [转载]Linux中文件查找技术大全