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