php怎么打印目录结构,c,php打印文件目录结构
时间: 2023-08-04 08:06:13 浏览: 45
PHP可以使用`scandir`函数来获取一个目录下的所有文件和子目录,然后递归打印出目录结构。以下是一个简单的示例代码:
```php
function printDir($dir, $indent = '') {
$files = scandir($dir);
foreach($files as $file) {
if ($file == '.' || $file == '..') continue;
echo $indent . $file . PHP_EOL;
if (is_dir($dir . '/' . $file)) {
printDir($dir . '/' . $file, $indent . ' ');
}
}
}
printDir('/path/to/directory');
```
上述代码中,`printDir`函数接收一个目录路径和一个缩进字符串。它首先使用`scandir`函数获取目录下的所有文件和子目录,并遍历每一个文件。如果文件名是`.`或`..`,则跳过。如果是一个子目录,则递归调用`printDir`函数,并传递缩进字符串加两个空格的形式作为参数,以便在打印时使用。最后打印出文件名和换行符。
对于C语言,可以使用`dirent.h`头文件提供的函数来读取目录。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <dirent.h>
void printDir(char *path, int indent) {
DIR *dir = opendir(path);
if (dir == NULL) return;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_name[0] == '.') continue;
for (int i = 0; i < indent; i++) {
putchar(' ');
}
printf("%s\n", entry->d_name);
if (entry->d_type == DT_DIR) {
char subpath[1024];
snprintf(subpath, sizeof(subpath), "%s/%s", path, entry->d_name);
printDir(subpath, indent + 2);
}
}
closedir(dir);
}
int main() {
printDir("/path/to/directory", 0);
return 0;
}
```
上述代码中,`printDir`函数接收一个目录路径和一个缩进量。它首先使用`opendir`函数打开目录,然后使用`readdir`函数读取目录下的每一个文件和子目录。如果文件名以`.`开头,则跳过。然后打印出文件名和缩进,如果是一个子目录,则递归调用`printDir`函数,传递缩进量加2的形式作为参数,以便在打印时使用。最后使用`closedir`函数关闭目录。