阅读量:2
readdir 函数本身并不支持递归读取目录,它只能读取指定目录下的文件和子目录。要实现递归目录读取,你需要结合 opendir、readdir 和 closedir 函数,并在遇到子目录时递归调用读取函数。以下是一个使用 C 语言实现的递归目录读取示例:
#include
#include
#include
#include
#include
void read_directory(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 st;
if (stat(full_path, &st) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(st.st_mode)) {
printf("Directory: %s\n", full_path);
read_directory(full_path); // 递归读取子目录
} else {
printf("File: %s\n", full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s \n" , argv[0]);
return 1;
}
read_directory(argv[1]);
return 0;
}
这个程序接受一个目录路径作为参数,然后递归地读取该目录及其所有子目录下的文件和目录。注意,这个示例没有处理符号链接和权限问题,实际使用时可能需要根据需求进行相应的处理。
以上就是关于“readdir如何实现递归目录读取”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm