阅读量:0
使用 readdir 函数可以实现对目录树的遍历。readdir 是 POSIX 标准中用于读取目录内容的函数。下面是一个简单的示例,展示如何使用 readdir 来遍历目录树。
#include
#include
#include
#include
#include
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[1024];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
struct stat path_stat;
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 \n" , argv[0]);
return EXIT_FAILURE;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
代码说明
- 打开目录:使用
opendir打开指定路径的目录。 - 读取目录项:通过
readdir循环读取目录中的每一项。 - 构建完整路径:使用
snprintf构建每个目录项的完整路径。 - 获取文件状态:使用
stat获取文件的状态信息,以判断是文件还是目录。 - 递归遍历:如果是目录,则递归调用
list_directory_contents函数。 - 关闭目录:使用
closedir关闭目录。
注意事项
- 这个示例代码没有处理符号链接,如果目录中包含符号链接,可能会导致无限递归。
- 错误处理部分使用了
perror来打印错误信息。 - 代码假设路径长度不超过 1024 字节,可以根据需要进行调整。
这个示例展示了如何使用 readdir 函数来遍历目录树,并打印出所有文件和子目录的路径。
以上就是关于“如何用readdir实现目录树遍历”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm