copendir
函數用于打開一個目錄流,以便讀取目錄中的條目。要實現目錄的遞歸遍歷,你需要結合 readdir
、closedir
和 opendir
函數。以下是一個使用 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 = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
struct dirent *entry;
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);
struct stat statbuf;
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
list_directory_contents(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;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
這個程序接受一個命令行參數,即要遍歷的目錄路徑。它首先打開目錄,然后讀取其中的每個條目。對于每個條目,它檢查是否為目錄。如果是目錄,則遞歸調用 list_directory_contents
函數;否則,打印文件的完整路徑。
注意:這個示例沒有處理符號鏈接和訪問權限問題。在實際應用中,你可能需要添加額外的邏輯來處理這些問題。