1 #pragma once
2 #include <sys/types.h>
3 
4 #if defined(__cplusplus)
5 extern  "C"  {
6 #endif
7 
8 /*
9  * This is a header for the common implementation of dirent
10  * to fs on-disk file type conversion.  Although the fs on-disk
11  * bits are specific to every file system, in practice, many
12  * file systems use the exact same on-disk format to describe
13  * the lower 3 file type bits that represent the 7 POSIX file
14  * types.
15  *
16  * It is important to note that the definitions in this
17  * header MUST NOT change. This would break both the
18  * userspace ABI and the on-disk format of filesystems
19  * using this code.
20  *
21  * All those file systems can use this generic code for the
22  * conversions.
23  */
24 
25 /*
26  * struct dirent file types
27  * exposed to user via getdents(2), readdir(3)
28  *
29  * These match bits 12..15 of stat.st_mode
30  * (ie "(i_mode >> 12) & 15").
31  */
32 
33 // 完整含义请见 http://www.gnu.org/software/libc/manual/html_node/Directory-Entries.html
34 #define S_DT_SHIFT	12
35 #define S_DT(mode)	(((mode) & S_IFMT) >> S_DT_SHIFT)
36 #define S_DT_MASK	(S_IFMT >> S_DT_SHIFT)
37 
38 /* these are defined by POSIX and also present in glibc's dirent.h */
39 #define DT_UNKNOWN	0
40 // 命名管道,或者FIFO
41 #define DT_FIFO		1
42 // 字符设备
43 #define DT_CHR		2
44 // 目录
45 #define DT_DIR		4
46 // 块设备
47 #define DT_BLK		6
48 // 常规文件
49 #define DT_REG		8
50 // 符号链接
51 #define DT_LNK		10
52 // 是一个socket
53 #define DT_SOCK		12
54 // 这个是抄Linux的,还不知道含义
55 #define DT_WHT		14
56 
57 #define DT_MAX		(S_DT_MASK + 1) /* 16 */
58 
59 #define DIR_BUF_SIZE 256
60 
61 /**
62  * @brief 文件夹结构体
63  *
64  */
65 struct DIR
66 {
67     int fd;
68     int buf_pos;
69     int buf_len;
70     char buf[DIR_BUF_SIZE];
71 
72     // todo: 加一个指向dirent结构体的指针
73 };
74 
75 struct dirent
76 {
77     ino_t d_ino;    // 文件序列号
78     off_t d_off;    // dir偏移量
79     unsigned short d_reclen;    // 目录下的记录数
80     unsigned char d_type;   // entry的类型
81     char d_name[];   // 文件entry的名字(是一个零长数组)
82 };
83 
84 /**
85  * @brief 打开文件夹
86  *
87  * @param dirname
88  * @return DIR*
89  */
90 struct DIR *opendir(const char *dirname);
91 
92 /**
93  * @brief 关闭文件夹
94  *
95  * @param dirp DIR结构体指针
96  * @return int 成功:0, 失败:-1
97 +--------+--------------------------------+
98 | errno  |              描述               |
99 +--------+--------------------------------+
100 |   0    |              成功               |
101 | -EBADF | 当前dirp不指向一个打开了的目录      |
102 | -EINTR |     函数执行期间被信号打断         |
103 +--------+--------------------------------+
104  */
105 int closedir(struct DIR *dirp);
106 
107 /**
108  * @brief 从目录中读取数据
109  *
110  * @param dir
111  * @return struct dirent*
112  */
113 struct dirent* readdir(struct DIR* dir);
114 
115 #if defined(__cplusplus)
116 }  /* extern "C" */
117 #endif