1 #include "dirent.h"
2 #include "unistd.h"
3 #include "stdio.h"
4 #include "fcntl.h"
5 #include "stddef.h"
6 #include "stdlib.h"
7 #include "string.h"
8 #include <libsystem/syscall.h>
9 
10 /**
11  * @brief 打开文件夹
12  *
13  * @param dirname
14  * @return DIR*
15  */
opendir(const char * path)16 struct DIR *opendir(const char *path)
17 {
18     int fd = open(path, O_DIRECTORY);
19     if (fd < 0) // 目录打开失败
20     {
21         printf("Failed to open dir\n");
22         return NULL;
23     }
24     // printf("open dir: %s\n", path);
25 
26     // 分配DIR结构体
27     struct DIR *dirp = (struct DIR *)malloc(sizeof(struct DIR));
28     // printf("dirp = %#018lx", dirp);
29     memset(dirp, 0, sizeof(struct DIR));
30     dirp->fd = fd;
31     dirp->buf_len = DIR_BUF_SIZE;
32     dirp->buf_pos = 0;
33 
34     return dirp;
35 }
36 
37 /**
38  * @brief 关闭文件夹
39  *
40  * @param dirp DIR结构体指针
41  * @return int 成功:0, 失败:-1
42 +--------+--------------------------------+
43 | errno  |              描述               |
44 +--------+--------------------------------+
45 |   0    |              成功               |
46 | -EBADF | 当前dirp不指向一个打开了的目录      |
47 | -EINTR |     函数执行期间被信号打断         |
48 +--------+--------------------------------+
49  */
closedir(struct DIR * dirp)50 int closedir(struct DIR *dirp)
51 {
52     int retval = close(dirp->fd);
53     free(dirp);
54     return retval;
55 }
56 
getdents(int fd,struct dirent * dirent,long count)57 int64_t getdents(int fd, struct dirent *dirent, long count)
58 {
59     return syscall_invoke(SYS_GET_DENTS, fd, (uint64_t)dirent, count, 0, 0, 0, 0, 0);
60 }
61 /**
62  * @brief 从目录中读取数据
63  *
64  * @param dir
65  * @return struct dirent*
66  */
readdir(struct DIR * dir)67 struct dirent *readdir(struct DIR *dir)
68 {
69     // printf("dir->buf = %#018lx\n", (dir->buf));
70     memset((dir->buf), 0, DIR_BUF_SIZE);
71     // printf("memeset_ok\n");
72     int len = getdents(dir->fd, (struct dirent *)dir->buf, DIR_BUF_SIZE);
73     // printf("len=%d\n", len);
74     if (len > 0)
75         return (struct dirent *)dir->buf;
76     else
77         return NULL;
78 }