0x01:首先讲一讲遍历文件夹必须要知道的一个结构体struct dirent{};
struct dirent{
ino_t d_ino; /* inode number */
off_t d_off; /* offset to next dirent */
unsigned short d_reclen; /* length of record */
unsigned char d_tpye; /*type of file;not support by all file system tpyes */
char d_name[256]; /*file name */
}
0x2:具体用法见如下代码query.c
#include <stdio.h>
#include <dirent.h>
int main(int argc, char **argv)
{
DIR *pDir = NULL;
struct dirent * pEnt = NULL;
unsigned int cnt = 0;
if (argc != 2)
{
printf("Please input directory name after %s\n", argv[0]);
return -1;
}
pDir = opendir(argv[1]);
if (NULL == pDir)
{
perror("opendir failed!\n");
return -1;
}
while (1)
{
pEnt = readdir(pDir);
if(pEnt != NULL)
{
// 还有子文件,在此处理子文件
printf("name:[%s] ,", pEnt->d_name);
cnt++;
if (pEnt->d_type == DT_REG)
{
printf("普通文件\n");
}
else
{
printf("非普通文件\n");
}
}
else //没有子文件,跳出循环
{
break;
}
};
printf("总文件数为:%d\n", cnt);
closedir(pDir);
return 0;
}
效果如下:
curtis@curtis-virtual-machine:~/Desktop/query_dir$ ./a.out /home/
name:[..] ,不是普通文件
name:[curtis] ,不是普通文件
name:[.] ,不是普通文件
总文件数为:3