readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。要使用 readdir 实现文件搜索,你需要遵循以下步骤:
#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", arg v[0]); return 1; } search_files(argv[1]); return 0; }
gcc file_search.c -o file_search ./file_search /path/to/search
这将输出指定目录及其子目录中的所有文件。你可以根据需要修改 search_files 函数,例如添加文件名匹配条件以仅搜索特定类型的文件。