readdir
函數是用于讀取目錄內容的 POSIX 標準函數,但它只能逐層讀取目錄中的條目,并不能直接遍歷整個目錄樹。如果你想要遍歷一個目錄樹(即遞歸地訪問目錄中的所有子目錄和文件),你需要結合使用 opendir
、readdir
和 closedir
函數,并在遇到子目錄時遞歸調用自己。
以下是一個簡單的 C 語言示例,展示了如何使用這些函數來遞歸遍歷目錄樹:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.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 == NULL) {
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 (stat(full_path, &path_stat) == -1) {
perror("stat");
continue;
}
// 如果是目錄,則遞歸調用
if (S_ISDIR(path_stat.st_mode)) {
printf("Directory: %s\n", full_path);
list_directory_contents(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;
}
// 開始遍歷
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
在這個示例中,list_directory_contents
函數接受一個目錄路徑作為參數,打開該目錄,并遍歷其中的所有條目。對于每個條目,它檢查是否是目錄,如果是,則遞歸調用自身;如果是文件,則打印文件名。注意,這個函數沒有處理符號鏈接,如果目錄中包含符號鏈接到子目錄的情況,可能會導致無限遞歸。
在使用這個程序時,你需要提供一個目錄路徑作為命令行參數,例如:
./listdir /path/to/directory
這將打印出指定目錄及其所有子目錄中的文件和目錄。