copendir如何遍歷目錄結(jié)構(gòu)

copendir如何遍歷目錄結(jié)構(gòu)

本文介紹如何利用 copendir 函數(shù)和 readdir 函數(shù)遞歸遍歷目錄結(jié)構(gòu)。 以下代碼示例展示了這一過程:

#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <string.h> #include <sys/stat.h> #include <limits.h> // Include for PATH_MAX  void traverseDirectory(const char *path) {     DIR *dir = opendir(path);     if (dir == NULL) {         perror("opendir");         return;     }      struct dirent *entry;     while ((entry = readdir(dir)) != NULL) {         if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {             continue; // Skip "." and ".." entries         }          char fullPath[PATH_MAX];         snprintf(fullPath, PATH_MAX, "%s/%s", path, entry->d_name);          struct stat statbuf;         if (stat(fullPath, &statbuf) == -1) {             perror("stat");             continue;         }          if (S_ISDIR(statbuf.st_mode)) {             printf("Directory: %sn", fullPath);             traverseDirectory(fullPath); // Recursive call for subdirectories         } else {             printf("File: %sn", fullPath);         }     }      closedir(dir); }  int main(int argc, char *argv[]) {     if (argc != 2) {         fprintf(stderr, "Usage: %s <directory>n", argv[0]);         return EXIT_FAILURE;     }      traverseDirectory(argv[1]);     return EXIT_SUCCESS; }

代碼功能說明:

  1. 打開目錄: opendir(path) 函數(shù)打開指定的目錄。
  2. 讀取目錄項: readdir(dir) 函數(shù)逐個讀取目錄中的文件和子目錄信息。
  3. 跳過特殊項: 代碼跳過 “.” (當(dāng)前目錄) 和 “..” (父目錄) 項。
  4. 構(gòu)建完整路徑: snprintf 函數(shù)構(gòu)建每個文件或子目錄的完整路徑。
  5. 獲取文件狀態(tài): stat(fullPath, &statbuf) 獲取文件狀態(tài)信息,用于判斷是文件還是目錄。
  6. 遞歸遍歷: 如果 statbuf 指示是目錄 (S_ISDIR),則遞歸調(diào)用 traverseDirectory 函數(shù)處理子目錄。
  7. 關(guān)閉目錄: closedir(dir) 關(guān)閉打開的目錄流,釋放資源。

使用方法:

  1. 將代碼保存為 .c 文件 (例如 listdir.c)。
  2. 使用 GCC 編譯: gcc -o listdir listdir.c
  3. 運行程序,并指定要遍歷的目錄路徑作為參數(shù): ./listdir /path/to/your/directory

此程序?qū)⒋蛴〕鲋付夸浖捌渌凶幽夸浿兴形募妥幽夸浀耐暾窂健? 請確保您具有訪問指定目錄的權(quán)限。 添加了 limits.h 頭文件和 PATH_MAX 常量,以確保路徑長度的正確處理,避免緩沖區(qū)溢出。

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點贊13 分享