阅读量:2
在Linux中,opendir函数用于打开一个目录流,以便后续使用其他相关函数(如readdir、closedir等)来遍历目录内容。以下是一个使用opendir和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[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->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 \n" , argv[0]);
return EXIT_FAILURE;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
代码说明:
opendir函数:打开指定路径的目录,并返回一个DIR指针。如果打开失败,返回NULL。readdir函数:从目录流中读取下一个目录项,并返回一个struct dirent指针。如果到达目录末尾,返回NULL。closedir函数:关闭目录流。stat函数:获取文件或目录的状态信息。- 递归遍历:如果遇到子目录,递归调用
list_directory_contents函数。
编译和运行:
gcc -o listdir listdir.c
./listdir /path/to/directory
这个程序会递归地遍历指定目录及其所有子目录,并打印出每个文件和目录的完整路径。
以上就是关于“如何用copendir实现Linux目录树遍历”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm