CDirIterator.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include "CDirIterator.h"
  2. #include <cerrno>
  3. CDirIterator::CDirIterator(const StringView& path, Flags flags)
  4. : m_flags(flags)
  5. {
  6. m_dir = opendir(String(path).characters());
  7. if (m_dir == nullptr) {
  8. m_error = errno;
  9. }
  10. }
  11. CDirIterator::~CDirIterator()
  12. {
  13. if (m_dir != nullptr) {
  14. closedir(m_dir);
  15. m_dir = nullptr;
  16. }
  17. }
  18. bool CDirIterator::advance_next()
  19. {
  20. if (m_dir == nullptr)
  21. return false;
  22. bool keep_advancing = true;
  23. while (keep_advancing) {
  24. errno = 0;
  25. auto* de = readdir(m_dir);
  26. if (de) {
  27. m_next = de->d_name;
  28. } else {
  29. m_error = errno;
  30. m_next = String();
  31. }
  32. if (m_next.is_null()) {
  33. keep_advancing = false;
  34. } else if (m_flags & Flags::SkipDots) {
  35. if (m_next.length() < 1 || m_next[0] != '.') {
  36. keep_advancing = false;
  37. }
  38. } else {
  39. keep_advancing = false;
  40. }
  41. }
  42. return m_next.length() > 0;
  43. }
  44. bool CDirIterator::has_next()
  45. {
  46. if (!m_next.is_null())
  47. return true;
  48. return advance_next();
  49. }
  50. String CDirIterator::next_path()
  51. {
  52. if (m_next.is_null())
  53. advance_next();
  54. auto tmp = m_next;
  55. m_next = String();
  56. return tmp;
  57. }