readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。要实现目录树的递归遍历,你需要结合 opendir、readdir 和 closedir 函数,并使用 stat 函数来检查文件类型。以下是一个简单的示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
void list_directory_contents(const char *path) {
DIR *dir = opendir(path);
struct dirent *entry;
struct stat path_stat;
if (!dir) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
snprintf(path_stat.path, sizeof(path_stat.path), "%s/%s", path, entry->d_name);
if (stat(path_stat.path, &path_stat) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(path_stat.st_mode)) {
printf("Directory: %s\n", path_stat.path);
list_directory_contents(path_stat.path);
} else {
printf("File: %s\n", path_stat.path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
list_directory_contents(argv[1]);
return 0;
}
这个程序接受一个目录作为命令行参数,并递归地列出该目录下的所有文件和子目录。注意,这个示例没有处理符号链接和其他特殊文件类型。在实际应用中,你可能需要根据需求进行相应的调整。