readdir 函數本身并不能直接實現目錄的遞歸遍歷,它只能讀取一個目錄下的內容。要實現目錄的遞歸遍歷,你需要結合其他函數,如 opendir、closedir 和 readdir,并使用遞歸方法來處理子目錄。
以下是一個使用 C 語言實現的遞歸遍歷目錄的示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void list_directory_contents(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat path_stat;
dir = opendir(path);
if (!dir) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
snprintf(path_stat.path, sizeof(path_stat.path), "%s/%s", path, entry->d_name);
if (stat(path_stat.path, &path_stat) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(path_stat.st_mode)) {
printf("Directory: %s\n", path_stat.path);
list_directory_contents(path_stat.path);
} else {
printf("File: %s\n", path_stat.path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]);
return EXIT_FAILURE;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
這個程序接受一個目錄路徑作為參數,并遞歸地列出該目錄及其所有子目錄中的文件和文件夾。注意,這個程序沒有處理符號鏈接,如果目錄中包含符號鏈接,可能會導致無限遞歸。要處理符號鏈接,你可以在調用 stat 之前檢查 entry->d_type 是否為 DT_LNK,并相應地處理。