readdir 是一個(gè)用于讀取目錄內(nèi)容的函數(shù),通常與 opendir、closedir 和其他文件操作函數(shù)一起使用。下面是一個(gè)簡(jiǎn)單的示例,展示了如何通過這些函數(shù)遍歷指定目錄及其子目錄中的所有文件和文件夾:
#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <sys/stat.h> #include <string.h> void list_directory_contents(const char *path) { DIR *dir; struct dirent *entry; struct stat path_stat; dir = opendir(path); if (dir == NULL) { perror("opendir"); return; } while ((entry = readdir(dir)) != NULL) { // 跳過當(dāng)前目錄(.)和上級(jí)目錄(..) if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } // 構(gòu)建完整路徑 char full_path[PATH_MAX]; snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name); // 獲取文件或目錄的信息 if (stat(full_path, &path_stat) == -1) { perror("stat"); continue; } // 輸出路徑名稱 printf("%sn", full_path); // 如果是目錄類型,則遞歸調(diào)用 if (S_ISDIR(path_stat.st_mode)) { list_directory_contents(full_path); } } closedir(dir); } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s <directory>n", argv[0]); return EXIT_FAILURE; } list_directory_contents(argv[1]); return EXIT_SUCCESS; } </string.h></sys/stat.h></dirent.h></stdlib.h></stdio.h>
該程序接收一個(gè)目錄路徑作為輸入?yún)?shù),并通過 opendir 打開目標(biāo)目錄。隨后利用 readdir 函數(shù)逐項(xiàng)讀取目錄內(nèi)容。在處理每個(gè)條目時(shí),通過 stat 函數(shù)獲取具體信息并輸出其完整路徑。若識(shí)別出子目錄,則會(huì)觸發(fā)遞歸操作繼續(xù)深入遍歷。
注意:此代碼未涉及符號(hào)鏈接或其他特殊文件類型的處理。實(shí)際開發(fā)中可根據(jù)需要增加相應(yīng)的判斷邏輯。
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載。
THE END