在linux系統里,readdir函數并未內置遞歸遍歷目錄的功能。它的主要作用是獲取指定目錄內的文件及子目錄信息。若要完成遞歸遍歷,則需自行構建遞歸函數來達成目標。
以下為一段采用c語言編寫的遞歸遍歷目錄結構的代碼示例:
#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <string.h> #include <sys/stat.h> void traverse_directory(const char *path) { DIR *dp; struct dirent *entry; struct stat file_stat; dp = opendir(path); if (!dp) { perror("opendir"); return; } while ((entry = readdir(dp)) != NULL) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } char full_path[1024]; snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name); if (lstat(full_path, &file_stat) == -1) { perror("lstat"); continue; } if (S_ISDIR(file_stat.st_mode)) { printf("Directory: %sn", full_path); traverse_directory(full_path); } else { printf("File: %sn", full_path); } } closedir(dp); } 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; }
此程序接收一個目錄路徑作為輸入參數,并以遞歸方式展示該目錄下所有的文件與子目錄。需要注意的是,本示例未涉及符號鏈接等特殊情況的處理,實際應用時應依據具體要求作出調整。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END