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("%sn", full_path); } } closedir(dir); }
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 函數,例如添加文件名匹配條件以僅搜索特定類型的文件。