阅读量:0
在Linux中,使用readdir函数可以实现递归目录遍历。以下是一个简单的示例,展示了如何使用readdir函数递归地遍历目录及其子目录:
#include
#include
#include
#include
#include
#include
void list_directory_contents(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat path_stat;
dir = opendir(path);
if (!dir) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
snprintf(path_stat.path, sizeof(path_stat.path), "%s/%s", path, entry->d_name);
if (stat(path_stat.path, &path_stat) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(path_stat.st_mode)) {
printf("Directory: %s\n", path_stat.path);
list_directory_contents(path_stat.path);
} else {
printf("File: %s\n", path_stat.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;
}
这个程序接受一个命令行参数,即要遍历的目录路径。它首先打开目录,然后读取目录中的每个条目。对于每个条目,它检查是否为目录。如果是目录,则递归调用list_directory_contents函数;如果是文件,则输出文件名。最后,关闭目录。
要编译此程序,请将其保存为recursive_directory_traversal.c,然后运行以下命令:
gcc -o recursive_directory_traversal recursive_directory_traversal.c
现在,您可以使用以下命令运行程序,其中是要遍历的目录路径:
./recursive_directory_traversal
请注意,这个示例程序没有处理符号链接、权限问题和其他潜在的错误情况。在实际应用中,您可能需要根据需要添加更多的错误处理和功能。
以上就是关于“Linux readdir如何实现递归目录遍历”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm