本文介紹如何利用 copendir 函數(shù)遍歷目錄。copendir 函數(shù)用于打開目錄并返回一個(gè) DIR 指針,方便訪問目錄中的文件和子目錄。以下示例演示了其基本用法:
#include <stdio.h> #include <stdlib.h> #include <dirent.h> int main() { DIR *dir; struct dirent *entry; // 打開當(dāng)前目錄 dir = opendir("."); if (dir == NULL) { perror("opendir failed"); return EXIT_FAILURE; } // 循環(huán)讀取目錄項(xiàng) while ((entry = readdir(dir)) != NULL) { printf("文件名: %s ", entry->d_name); } // 關(guān)閉目錄 closedir(dir); return EXIT_SUCCESS; }
代碼首先包含必要的頭文件,然后使用 opendir(“.”) 打開當(dāng)前目錄。 opendir 函數(shù)成功返回一個(gè) DIR 指針,否則返回 NULL 并打印錯(cuò)誤信息。 readdir 函數(shù)循環(huán)讀取目錄項(xiàng),每次返回一個(gè) dirent 結(jié)構(gòu)體指針,包含文件名等信息。 循環(huán)結(jié)束條件是 readdir 返回 NULL,表示已讀取所有目錄項(xiàng)。最后,closedir 關(guān)閉目錄,釋放資源。
請(qǐng)注意,實(shí)際應(yīng)用中需要添加錯(cuò)誤處理和更完善的邏輯,例如處理子目錄(可能需要遞歸調(diào)用)以及區(qū)分文件和目錄等。 本例僅展示了 copendir 的基本使用方法。