参考网站: opendir函数和readdir函数内涵及用法
struct dirent
头文件 : dirent.h
struct dirent { ino_t d_ino; off_t d_off; unsigned short d_reclen; unsigned char d_type; char d_name[256]; };
这个函数用来定义一个变量,用来接收文件,读取文件等等文件操作。
d_type
unsigned char d_type
This is the type of the file, possibly unknown. The following constants are defined for its value:
DT_UNKNOWN The type is unknown. Only some filesystems have full support to return the type of the file, others might always return this value.
类型未知。少数文件系统会出现此函数不支持的文件类型,另一些则总是返回这个值。译者注:总之这个值是为了应对不兼容的文件系统而设置的。
d_type表示档案类型:
enum
{
DT_UNKNOWN = 0,
# define DT_UNKNOWN DT_UNKNOWN
DT_FIFO = 1,
# A named pipe, or FIFO. See FIFO Special Files.
# define DT_FIFO DT_FIFO
DT_CHR = 2,
#字符设备
# define DT_CHR DT_CHR
DT_DIR = 4,
#目录
# define DT_DIR DT_DIR
DT_BLK = 6,
# 块设备
# define DT_BLK DT_BLK
DT_REG = 8,
#常规文件
# define DT_REG DT_REG
DT_LNK = 10,
# 符号链接
# define DT_LNK DT_LNK
DT_SOCK = 12,
#套接字
# define DT_SOCK DT_SOCK
DT_WHT = 14
# define DT_WHT DT_WHT
};
char d_name[]
char d_name[] 文件条目
文件名长度不应该超NAME_MAX
NAME_MAX 在limits.h中定义为: #define NAME_MAX 255
opendir函数
头文件:#include <sys/types.h> #include <dirent.h>
函数:DIR *opendir(const char *name);
含义: 简而言之就是打开目标文件。
关于DIR : 详细:http://blog.csdn.net/u012349696/article/details/50083787
DIR结构体类似于FILE,是一个内部结构,以下几个函数用这个内部结构保存当前正在被读取的目录的有关信息(摘自《UNIX环境高级编程(第二版)》)。函数 DIR *opendir(const char *pathname),即打开文件目录,返回的就是指向DIR结构体的指针,而该指针由以下几个函数使用:
struct dirent *readdir(DIR *dp);
void rewinddir(DIR *dp);
int closedir(DIR *dp);
long telldir(DIR *dp);
void seekdir(DIR *dp,long loc);
先说说DIR这一结构体,以下为DIR结构体的定义:
struct __dirstream
{
void *__fd;
char *__data;
int __entry_data;
char *__ptr;
int __entry_ptr;
size_t __allocation;
size_t __size;
__libc_lock_define (, __lock)
};typedef struct __dirstream DIR;
readdir函数
头文件:#include<sys/types.h> #include <dirent.h>
函数:struct dirent *readdir(DIR *dir);
含义:readdir()返回参数dir 目录流的下个目录进入点。即读取文件。
closedir函数
头文件:#include<sys/types.h> #include <dirent.h>
函数:closedir(DIR *dir);
含义:关闭dir流 ;
代码举例以及分析
struct node *list = list_init("1.mp3");
//这是已经定义好的一个链表的初始化函数:建立一个链头,将数据赋值为:"1.mp3"。
char *path = "/mnt/udisk/MusicJF/";
DIR *dp = opendir(path);
//打开路径path,将文件下的数据转换成目录流赋值给dp
struct dirent *p;
while(p = readdir(dp)) //遍历目录文件
{
if(p->d_type == DT_REG)//是否为常规文件
{
if(strstr(p->d_name,".mp3")) //判断是否为.mp3文件
{
struct node *new = newnode(p->d_name); //创建新节点
addnode(new,list); //插入新节点
}
}
}