
readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。要使用 readdir 实现文件搜索,你需要遵循以下步骤:
- 包含必要的头文件:
#<span>include <stdio.h></span> #<span>include <stdlib.h></span> #<span>include <dirent.h></span> #<span>include <string.h></span>
- 编写一个递归函数,该函数接受一个目录路径作为参数,并使用 opendir、readdir 和 closedir 函数来遍历目录及其子目录:
void search_files(<span>const char *path)</span> {
DIR *dir;
<span>struct dirent *entry;</span>
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
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);
if (entry->d_type == DT_DIR) {
search_files(full_path);
} else {
printf("%s\n", full_path);
}
}
closedir(dir);
}
- 在 main 函数中调用 search_files 函数,传入要搜索的目录路径:
int main(<span>int argc, char *argv[])</span> {
if (argc < 2) {
printf("Usage: %s <directory_path>\n", argv[0]);
return 1;
}
search_files(argv[1]);
return 0;
}
- 编译并运行程序:
gcc file_search.c -o file_search ./file_search /path/to/search
这将输出指定目录及其子目录中的所有文件。你可以根据需要修改 search_files 函数,例如添加文件名匹配条件以仅搜索特定类型的文件。










