readdir
是一個用于讀取目錄內容的函數,通常在 C 語言中使用。要使用 readdir
實現文件搜索,你需要遵循以下步驟:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
opendir
、readdir
和 closedir
函數來遍歷目錄及其子目錄: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);
}
main
函數中調用 search_files
函數,傳入要搜索的目錄路徑:int main(int argc, char *argv[]) {
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
函數,例如添加文件名匹配條件以僅搜索特定類型的文件。