dirent.c 1.8 KB

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