readdir
函數本身不會遞歸地讀取子目錄。它只能讀取指定目錄下的文件和子目錄。如果你想要遞歸地讀取子目錄,你需要自己編寫一個遞歸函數來實現這個功能。
下面是一個簡單的示例,展示了如何使用 readdir
函數遞歸地讀取目錄及其子目錄中的所有文件:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void read_directory_recursive(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
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;
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)) {
read_directory_recursive(full_path);
} else {
printf("%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;
}
這個程序接受一個目錄路徑作為參數,并遞歸地讀取該目錄及其子目錄中的所有文件。注意,這個示例程序沒有處理符號鏈接和其他可能的錯誤情況。在實際應用中,你可能需要根據你的需求進行相應的調整。