如何用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 分享