readdir如何實現遞歸遍歷

readdir如何實現遞歸遍歷

readdir 函數本身并不提供遞歸遍歷目錄的功能,它只是用于讀取指定目錄下的文件和子目錄。要實現遞歸遍歷,你需要結合 readdir 和其他函數(如 opendir、closedir 和 stat)來完成。以下是一個使用 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;     <span>struct dirent *entry;</span>     <span>struct stat path_stat;</span>      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;         }          if (S_ISDIR(path_stat.st_mode)) {             printf("Directory: %sn", path_stat.path);             list_directory_contents(path_stat.path);         } else {             printf("File: %sn", path_stat.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; } 

這個程序接受一個目錄路徑作為命令行參數,然后遞歸地遍歷該目錄及其所有子目錄,打印出所有文件和目錄的路徑。注意,這個程序沒有處理符號鏈接和權限問題,實際使用時可能需要根據需求進行相應的修改。

? 版權聲明
THE END
喜歡就支持一下吧
點贊6 分享