dirent.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. * @brief 打开文件夹
  11. *
  12. * @param dirname
  13. * @return DIR*
  14. */
  15. struct DIR *opendir(const char *path)
  16. {
  17. int fd = open(path, O_DIRECTORY);
  18. if (fd < 0) // 目录打开失败
  19. return NULL;
  20. // 分配DIR结构体
  21. struct DIR *dirp = (struct DIR *)malloc(sizeof(struct DIR));
  22. memset(dirp, 0, sizeof(struct DIR));
  23. dirp->fd = fd;
  24. dirp->buf_len = DIR_BUF_SIZE;
  25. dirp->buf_pos = 0;
  26. return dirp;
  27. }
  28. /**
  29. * @brief 关闭文件夹
  30. *
  31. * @param dirp DIR结构体指针
  32. * @return int 成功:0, 失败:-1
  33. +--------+--------------------------------+
  34. | errno | 描述 |
  35. +--------+--------------------------------+
  36. | 0 | 成功 |
  37. | -EBADF | 当前dirp不指向一个打开了的目录 |
  38. | -EINTR | 函数执行期间被信号打断 |
  39. +--------+--------------------------------+
  40. */
  41. int closedir(struct DIR *dirp)
  42. {
  43. int retval = close(dirp->fd);
  44. free(dirp);
  45. return retval;
  46. }
  47. int64_t getdents(int fd, struct dirent *dirent, long count)
  48. {
  49. return syscall_invoke(SYS_GET_DENTS, fd, (uint64_t)dirent, count, 0, 0, 0, 0, 0);
  50. }
  51. /**
  52. * @brief 从目录中读取数据
  53. *
  54. * @param dir
  55. * @return struct dirent*
  56. */
  57. struct dirent *reaaddir(struct DIR *dir)
  58. {
  59. memset(dir, 0, DIR_BUF_SIZE);
  60. int len = getdents(dir->fd, (struct dirent *)dir->buf, DIR_BUF_SIZE);
  61. if (len > 0)
  62. return (struct dirent *)dir->buf;
  63. else
  64. return NULL;
  65. }