readdir和scandir两个函数均可读取目录下所有文件。
struct dirent *readdir(DIR *dirp):返回指向下一个节点的指针,如果没有下一个节点,则返回NULL。
int scandir(const char *dirp, struct dirent ***namelist, int (*filter)(const struct dirent *), int (*compar)(const struct dirent **, const struct dirent **)):扫描整个目录,并使用filter进行过滤,过滤后的结果存在malloc分配的缓存里,并可以通过compar进行排序,或自定义处理。
在不确定目录下有多少文件的时候,不建议用scandir。
示例程序如下:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
/*****************************************************************************
*
* Macro definition
*
*****************************************************************************/
/*****************************************************************************
*
* Structure/Class definition
*
*****************************************************************************/
/*****************************************************************************
*
* Data definition
*
*****************************************************************************/
/*****************************************************************************
*
* Function Entity
*
*****************************************************************************/
void PrintNodeType(unsigned char type) {
switch (type)
{
case DT_BLK:
printf("This is a block device.\r\n");
break;
case DT_CHR:
printf("This is a character device.\r\n");
break;
case DT_DIR:
printf("This is a directory.\r\n");
break;
case DT_FIFO:
printf("This is a named pipe (FIFO).\r\n");
break;
case DT_LNK:
//printf("This is a symbolic link.\r\n");
break;
case DT_REG:
printf("This is a regular file.\r\n");
break;
case DT_SOCK:
printf("This is a UNIX domain socket.\r\n");
break;
case DT_UNKNOWN:
printf("The file type is unknown.\r\n");
break;
default:
break;
}
}
//
int UseReaddir(const char *path) {
DIR *dir;
struct dirent *node_info;
//
if((dir = opendir(path)) == NULL){
printf("opendir %s ERR\r\n",path);
return -1;
}
//
while((node_info = readdir(dir)) != NULL) {
// 跳过'.'、'..',以及隐藏文件
//if(strncmp(node_info->d_name, ".", 1) == 0) {
// continue;
//}
//PrintNodeType(node_info->d_type);
printf("%s\r\n", node_info->d_name);
}
return 0;
}
//
int UseScandir(const char *path) {
struct dirent **node_info;
int node_num;
int i;
//
node_num = scandir(path, &node_info, 0, alphasort);
if (node_num < 0) {
printf("opendir %s ERR\r\n",path);
return -1;
}
//
for (i = 0; i < node_num; ++ i) {
// 跳过'.'、'..',以及隐藏文件
//if(strncmp(node_info->d_name, ".", 1) == 0) {
// continue;
//}
//PrintNodeType(node_info[i]->d_type);
printf("%s\r\n", node_info[i]->d_name);
free(node_info[i]);
}
free(node_info);
return 0;
}
//
int main(int argc, char **argv) {
if (argc != 2) {
printf("%s path\r\n", argv[0]);
return 1;
}
//
printf("\r\n");
UseReaddir(argv[1]);
//
printf("\r\n");
UseScandir(argv[1]);
return 0;
}