readdir
函數本身并不支持遞歸讀取目錄,它只能讀取指定目錄下的文件和子目錄。要實現遞歸讀取目錄,你需要結合其他函數,如 opendir
、readdir
和 closedir
,并在遍歷過程中檢查每個條目是否為目錄,如果是目錄,則遞歸調用讀取函數。
以下是一個使用 C 語言實現的遞歸讀取目錄的示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void read_directory_recursive(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
if (!(dir = opendir(path))) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (lstat(full_path, &statbuf) == -1) {
perror("lstat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
printf("Directory: %s\n", full_path);
read_directory_recursive(full_path);
} else {
printf("File: %s\n", full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
read_directory_recursive(argv[1]);
return EXIT_SUCCESS;
}
這個程序接受一個目錄路徑作為命令行參數,并遞歸地讀取該目錄及其子目錄下的所有文件和目錄。注意,這個示例使用了 lstat
函數而不是 stat
函數,以避免在處理符號鏈接時出現問題。