温馨提示×

Linux readdir如何实现目录递归遍历

小樊
48
2025-07-12 11:06:40
栏目: 智能运维

在Linux中,要实现目录的递归遍历,可以使用readdir函数结合其他相关函数。以下是一个使用C语言编写的示例程序,展示了如何使用readdir函数递归遍历目录:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #include <sys/stat.h> #include <unistd.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; char full_path[PATH_MAX]; snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name); if (lstat(full_path, &path_stat) == -1) { perror("lstat"); 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(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; } 

解释

  1. opendir: 打开一个目录流。
  2. readdir: 读取目录流中的下一个条目。
  3. lstat: 获取文件或目录的状态信息。
  4. S_ISDIR: 检查文件是否为目录。
  5. 递归调用: 如果遇到子目录,则递归调用list_directory_contents函数。

编译和运行

使用以下命令编译程序:

gcc -o listdir listdir.c 

然后运行程序并指定要遍历的目录:

./listdir /path/to/directory 

这个程序会递归地遍历指定目录及其所有子目录,并打印出每个文件和目录的完整路径。

0