copendir 是一個用于打開目錄的函數,它返回一個指向 DIR 結構的指針,該結構包含了目錄流的信息。在遞歸遍歷目錄時,copendir 通常與 readdir 和 closedir 函數一起使用,以讀取目錄內容并檢查每個條目是否為子目錄。如果是子目錄,則遞歸調用遍歷函數。
以下是一個使用 copendir 遞歸遍歷目錄的示例代碼:
#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 == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
// Skip current and parent directory entries
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// Construct the full path of the entry
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
// Get the file status
if (stat(full_path, &path_stat) == -1) {
perror("stat");
continue;
}
// If it's a directory, recurse
if (S_ISDIR(path_stat.st_mode)) {
printf("Directory: %s\n", full_path);
list_directory_contents(full_path);
} else {
// Otherwise, print the file name
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 函數接受一個目錄路徑作為參數,打開該目錄,并使用 readdir 函數讀取其內容。對于每個條目,它使用 stat 函數獲取文件狀態,以確定它是文件還是目錄。如果是目錄,它會打印目錄名并遞歸調用自身。如果是文件,它將打印文件名。注意,這個函數會跳過當前目錄(.)和父目錄(..)的條目。
要使用這個程序,你需要將其編譯為可執行文件,并在命令行中提供要遍歷的目錄路徑作為參數。例如:
gcc -o listdir listdir.c
./listdir /path/to/directory
這將遞歸地列出指定目錄及其所有子目錄中的文件和目錄。