在 Linux 系统中,opendir
函数用于打开一个目录流,以便读取目录中的条目。要实现目录的递归遍历,可以结合使用 readdir
、closedir
和 opendir
函数。以下是一个示例代码,演示如何使用这些函数递归遍历目录:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void list_directory_contents(const char *path);
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]);
return EXIT_FAILURE;
}
const char *path = argv[1];
list_directory_contents(path);
return EXIT_SUCCESS;
}
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 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); // Recursive call for subdirectory
} else {
printf("File: %s\n", full_path);
}
}
closedir(dir);
}
主函数 (main
):
list_directory_contents
函数开始递归遍历。list_directory_contents
函数:
opendir
打开指定路径的目录。opendir
是否成功,如果失败则打印错误信息并返回。readdir
逐个读取目录中的条目。.
) 和上级目录 (..
)。snprintf
构建条目的完整路径。stat
获取条目的状态信息,判断是文件还是目录。
list_directory_contents
。closedir
关闭目录流。将上述代码保存为 recursive_directory_traversal.c
,然后使用以下命令编译和运行:
gcc -o recursive_directory_traversal recursive_directory_traversal.c
./recursive_directory_traversal /path/to/directory
替换 /path/to/directory
为你想要遍历的目标目录路径。运行后,程序将递归地列出该目录及其所有子目录中的文件和子目录。
错误处理:代码中包含基本的错误处理,例如检查 opendir
和 stat
的返回值。根据需要,可以添加更多的错误处理逻辑。
符号链接:上述代码不会特别处理符号链接。如果目录中包含符号链接,并且链接指向父目录或自身,可能会导致无限递归。可以通过检查 S_ISLNK
标志来避免这种情况。
性能优化:对于非常大的目录结构,递归方法可能会导致栈溢出。可以考虑使用非递归的方法(如使用显式栈或队列)来实现目录遍历。
希望这个示例对你有所帮助!