readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。要使用 readdir 实现目录的深度优先搜索(DFS),你可以结合递归的方法来遍历子目录。以下是一个简单的示例代码,演示如何使用 readdir 和递归来实现目录的深度优先搜索:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
void dfs(const char *path) {
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 忽略当前目录和父目录的特殊条目
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 构建完整的路径
char full_path[1024];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
struct stat statbuf;
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
// 如果是目录,则递归调用 dfs
if (S_ISDIR(statbuf.st_mode)) {
dfs(full_path);
} else {
// 如果是文件,则打印文件名
printf("%s\n", full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
dfs(argv[1]);
return EXIT_SUCCESS;
}
打开目录:使用 opendir 打开指定路径的目录。
读取目录项:使用 readdir 读取目录中的每一项。
构建完整路径:对于每个目录项,构建其完整路径。
检查文件类型:使用 stat 获取文件信息,并判断该项是文件还是目录。
递归遍历:如果是目录,则递归调用 dfs 函数;如果是文件,则打印文件名。
关闭目录:使用 closedir 关闭目录。
编译并运行程序,传入要搜索的目录作为参数:
gcc -o dfs_directory dfs_directory.c
./dfs_directory /path/to/directory
这段代码会打印出指定目录及其所有子目录中的文件路径,采用深度优先搜索的方式遍历目录结构。