温馨提示×

Linux readdir如何实现子目录遍历

小樊
54
2025-05-20 20:13:51
栏目: 智能运维

在Linux中,使用readdir函数可以实现子目录遍历。readdir函数是POSIX标准库中的一个函数,用于读取目录中的条目。以下是一个简单的示例,展示了如何使用readdir函数遍历目录及其子目录:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #include <sys/stat.h> 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; } printf("%s\n", path_stat_path); if (S_ISDIR(path_stat.st_mode)) { list_directory_contents(path_stat_path); } } closedir(dir); } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s <directory>\n", argv[0]); return EXIT_FAILURE; } list_directory_contents(argv[1]); return EXIT_SUCCESS; } 

这个程序接受一个目录路径作为参数,然后使用readdir函数遍历该目录及其子目录。对于每个目录条目,我们首先检查它是否是...,然后使用stat函数获取条目的详细信息。如果条目是一个目录,我们递归地调用list_directory_contents函数来遍历子目录。

要编译此程序,请使用以下命令:

gcc -o list_directory_contents list_directory_contents.c 

然后运行程序,传入要遍历的目录路径:

./list_directory_contents /path/to/directory 

这将输出指定目录及其子目录中的所有文件和目录。

0