opendir 函数用于打开一个目录流,而 readdir 函数用于读取目录中的条目。要实现目录的递归遍历,你需要结合这两个函数,并对子目录进行递归调用。
以下是一个使用 opendir 和 readdir 实现目录递归遍历的示例代码(C语言):
#<span>include <stdio.h></span>
#<span>include <stdlib.h></span>
#<span>include <string.h></span>
#<span>include <dirent.h></span>
#<span>include <sys/stat.h></span>
void list_directory_contents(<span>const char *path)</span> {
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
<span>struct dirent *entry;</span>
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);
<span>struct stat path_stat;</span>
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(<span>int argc, char *argv[])</span> {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]);
return EXIT_FAILURE;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
这个程序接受一个命令行参数作为要遍历的目录路径。list_directory_contents 函数会打开目录,读取其中的条目,并检查每个条目是文件还是子目录。如果是子目录,它会递归调用自身以继续遍历子目录的内容。
编译并运行这个程序,传入一个目录路径作为参数,它将打印出该目录及其所有子目录中的文件和目录。
以上就是如何用copendir实现目录递归遍历的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号