Linux C 中的目錄操作

2021-06-08 01:35:20 字數 768 閱讀 1483

linux的目錄操作一般流程為:開啟目錄-讀取目錄(中的檔案)-關閉目錄。相應的函式為opendir-readdir-closedir,其原型都在/usr/include/dirent.h中定義。

原型:#include

dir *opendir(const char *dirname);

struct dirent *readdir(dir *dirp);

int closedir(dir *dirp);

dir是directory stream,opendir函式返回dir流型別並供讀取函式readdir呼叫;

readdir返回dirent結構體:

struct dirent

;d_reclen表示記錄長度,d_type表示檔案型別(具體見後面),d_name表示檔名;

closedir返回0表示關閉成功,-1表示失敗。

dirent結構體中的d_tpye的值可以為以下列舉成員:

enum

; 示例:

#include

string testpath;

dir* pdir = null;

struct dirent* ent = null;

pdir = opendir(testpath.c_str());

if (null == pdir)

while (null != (ent=readdir(pdir)))

}...

closedir(pdir);

pdir = null;

Linux c 目錄操作函式scandir

include int scandir const char dir,struct dirent namelist,int filter const void b int compare const struct dirent const struct dirent int alphasort co...

Linux c目錄操作函式scandir

strdup,strndup,scandir等內部呼叫了malloc,需要手動釋放記憶體。標頭檔案 include 函式定義 int scandir const char dir,struct dirent namelist,int filter const void b int compare c...

Linux c 目錄操作函式scandir

標頭檔案 include 函式定義 int scandir const char dir,struct dirent namelist,int filter const void b int compare const struct dirent const struct dirent int al...