在linux下遍歷某一目錄下內(nèi)容LINUX下歷遍目錄的方法一般是這樣的
打開(kāi)目錄->讀取->關(guān)閉目錄
相關(guān)函數(shù)是opendir -> readdir -> closedir,其原型如下:
#include <dirent.h>
DIR *opendir(const char *dirname);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
簡(jiǎn)單列舉一例:
#include<dirent.h>
struct dirent* ent = NULL;
DIR *pDir;
if( (pDir=opendir("/home/test")) == NULL)
{
printf("open dir %s failed\n", pszBaseDir);
return false;
}
while( (ent=readdir(pDir)) != NULL )
{
printf("the ent->d_reclen is%d the ent->d_type is%d the ent->d_name is%s\n", ent->d_reclen, ent->d_type, ent->d_name);
}
closedir(pDir);
其中有一很關(guān)鍵的結(jié)構(gòu)體dirent:

代碼
On Linux, the dirent structure is defined as follows:
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file */
char d_name[256]; /* filename */
};
其中inode表示存放的是該文件的結(jié)點(diǎn)數(shù)目(具體可了解linux下的文件系統(tǒng)),d_off 是文件在目錄中的編移,這兩個(gè)基本很少用。
d_type表示檔案類型:
04 |
# define DT_UNKNOWN DT_UNKNOWN |
06 |
# define DT_FIFO DT_FIFO |
08 |
# define DT_CHR DT_CHR |
10 |
# define DT_DIR DT_DIR |
12 |
# define DT_BLK DT_BLK |
14 |
# define DT_REG DT_REG |
16 |
# define DT_LNK DT_LNK |
18 |
# define DT_SOCK DT_SOCK |
20 |
# define DT_WHT DT_WHT |
d_reclen認(rèn)為是紀(jì)錄的長(zhǎng)度,計(jì)算方式應(yīng)該是4(d_ino)+4(d_off)+2(d_reclen)+1(d_type)+1(補(bǔ)齊位)+4N(d_name會(huì)自動(dòng)補(bǔ)齊:1.jpg為8,12.jpg也為8,1234.jpg也為8,12345.jpg則為12);所以一般d_reclen是20和24(其中.和..是16)。
d_name表示文件名,如test.jpg