在 Linux 中,copendir
函数本身并不提供递归遍历目录的功能。copendir
用于打开一个目录流,以便后续使用 readdir
等函数读取目录内容。要实现递归遍历目录,你需要结合使用 opendir
、readdir
和 closedir
函数,并在遇到子目录时递归调用遍历函数。
以下是一个使用 C 语言实现的递归遍历目录的示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void list_directory_contents(const char *path) {
struct dirent *dp;
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
return;
}
while ((dp = readdir(dir)) != NULL) {
if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) {
continue;
}
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, dp->d_name);
struct stat statbuf;
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.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;
}
这个程序接受一个目录路径作为命令行参数,并递归地列出该目录下的所有文件和子目录。注意,这个示例没有处理符号链接和访问权限问题,实际使用时可能需要根据需求进行调整。