如何用copendir遍歷目錄文件

如何用copendir遍歷目錄文件

opendir 函數(shù)是 C 語言中用于打開目錄的函數(shù),通常與 readdir 和 closedir 函數(shù)配合使用,實(shí)現(xiàn)對目錄下文件和子目錄的遍歷。以下示例演示了如何使用這三個(gè)函數(shù)遍歷指定目錄:

#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <string.h>  int main() {     DIR *dir;     struct dirent *entry;     char *dir_path = "."; //  遍歷當(dāng)前目錄,可修改為其他路徑      // 打開目錄     dir = opendir(dir_path);     if (dir == NULL) {         perror("opendir");         return EXIT_FAILURE;     }      // 遍歷目錄內(nèi)容     while ((entry = readdir(dir)) != NULL) {         printf("%sn", entry->d_name);     }      // 關(guān)閉目錄     closedir(dir);      return EXIT_SUCCESS; }

代碼首先包含必要的頭文件,然后定義一個(gè)指向目錄路徑的指針 dir_path,此處默認(rèn)為當(dāng)前目錄 “.”,可根據(jù)需要修改為其他路徑。opendir 函數(shù)打開指定目錄,成功則返回 DIR 指針,失敗則返回 NULL 并打印錯(cuò)誤信息。 readdir 函數(shù)在循環(huán)中逐個(gè)讀取目錄項(xiàng),直到返回 NULL 表示遍歷結(jié)束。 每個(gè)目錄項(xiàng)的信息存儲(chǔ)在 dirent 結(jié)構(gòu)體中,此處僅打印文件名 entry->d_name。最后,closedir 函數(shù)關(guān)閉目錄,釋放資源。

需要注意的是,該示例只打印文件名。若需獲取文件類型、大小等更多信息,可結(jié)合 stat 函數(shù)使用。 此外,. 和 .. 分別代表當(dāng)前目錄和父目錄,通常需要在遍歷時(shí)進(jìn)行過濾。

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