本文介绍如何利用Linux系统下的标准C库函数opendir、readdir和closedir实现目录的递归遍历。 虽然这些函数本身并不支持递归,但我们可以通过编写递归函数来完成此功能。
以下代码示例演示了如何使用这些函数递归遍历给定目录:
#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <string.h> #include <sys/stat.h> void traverseDirectory(const char *path) { DIR *dir; struct dirent *entry; struct stat path_stat; // 打开目录 dir = opendir(path); if (dir == NULL) { perror("opendir"); return; } // 遍历目录条目 while ((entry = readdir(dir)) != NULL) { // 跳过"."和".." if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; // 构建完整路径 char fullPath[PATH_MAX]; snprintf(fullPath, sizeof(fullPath), "%s/%s", path, entry->d_name); // 获取文件/目录信息 if (stat(fullPath, &path_stat) == -1) { perror("stat"); continue; } // 递归处理子目录 if (S_ISDIR(path_stat.st_mode)) { printf("目录: %s\n", fullPath); traverseDirectory(fullPath); } else { // 打印文件 printf("文件: %s\n", fullPath); } } // 关闭目录 closedir(dir); } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "用法: %s <目录路径>\n", argv[0]); return EXIT_FAILURE; } traverseDirectory(argv[1]); return EXIT_SUCCESS; }
代码说明:
编译和运行:
将代码保存为例如recursive_traversal.c,然后使用以下命令编译和运行:
gcc -o recursive_traversal recursive_traversal.c ./recursive_traversal /path/to/your/directory
将/path/to/your/directory替换成你想要遍历的目录路径。 程序会递归地列出该目录及其所有子目录下的文件和目录。
这个改进后的版本使用了更清晰的变量名和注释,并对代码结构进行了微调,使其更易于理解和维护。
以上就是如何用copendir实现Linux目录的递归遍历的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号