如何用copendir实现目录递归遍历

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: %sn", full_path);             list_directory_contents(full_path);         } else {             printf("File: %sn", 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 函数会打开目录,读取其中的条目,并检查每个条目是文件还是子目录。如果是子目录,它会递归调用自身以继续遍历子目录的内容。

编译并运行这个程序,传入一个目录路径作为参数,它将打印出该目录及其所有子目录中的文件和目录。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享