Linux readdir如何實現遞歸遍歷

linux系統中,利用readdir函數可以實現目錄的遞歸遍歷。下面是一個示例代碼,展示了如何通過readdir和opendir等函數來遞歸遍歷目錄及其子目錄:

#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <String.h> #include <sys/stat.h>  void traverse_directory(const char *path) {     DIR *dir;     struct dirent *entry;     struct stat path_stat;     char path_stat_path[1024];      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);             traverse_directory(path_stat_path);         } else {             printf("File: %sn", 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;     }      traverse_directory(argv[1]);      return EXIT_SUCCESS; }

代碼解析

  1. 頭文件包含

    • stdio.h:用于標準輸入輸出操作。
    • stdlib.h:用于標準庫函數。
    • dirent.h:用于目錄操作。
    • string.h:用于字符串操作。
    • sys/stat.h:用于獲取文件狀態信息。
  2. traverse_directory函數

    • 接受一個目錄路徑作為參數。
    • 使用opendir打開目錄。
    • 使用readdir讀取目錄中的條目。
    • 對每個條目,使用stat獲取文件狀態信息。
    • 如果條目是目錄,則遞歸調用traverse_directory。
    • 如果條目是文件,則打印文件路徑。
    • 最后關閉目錄。
  3. main函數

    • 檢查命令行參數,確保提供了一個目錄路徑。
    • 調用traverse_directory函數開始遞歸遍歷。

編譯與執行

使用以下命令編譯程序:

gcc -o listdir listdir.c

然后運行程序并指定要遍歷的目錄:

./listdir /path/to/directory

該程序將遞歸地遍歷指定的目錄及其所有子目錄,并打印每個文件和目錄的路徑。

Linux readdir如何實現遞歸遍歷

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