[原创] Tips: 两种目录遍历的方法
来源:互联网 发布:数据库空间 编辑:程序博客网 时间:2024/05/22 20:09
目录的遍历是个老问题,主要用在目录遍历类操作,比如删除、统计磁盘占用等等情况。目录就是一个典型的树形结构,递归是最简单的方法了。
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遍历文件夹的两种方法
- 两种遍历二维数组的方法
- 用Delphi编写点对点传文件程序
- 基于WinSocket的网络通信实现
- ::多层结构连接方式选择的分析::
- 如何利用C++ Builder 5.0 Enterprise 创建用户自己的网上聊天程序
- 非阻塞方式下Socket读取数据的一个例子
- [原创] Tips: 两种目录遍历的方法
- Socket 编程简介
- socket编程原理
- 用Socket接口实现网络异步通信
- 基于Socket的聊天室实现原理
- [转]FTP搜索引擎的设计与实现(优化版)
- 将Socket应用程序从Unix向Windows移植中应注意的几点问题
- socket的工作模式
- Linux程式设计入门 - socket/inetd programming