DirIterator.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Vector.h>
  8. #include <LibCore/DirIterator.h>
  9. #include <errno.h>
  10. namespace Core {
  11. DirIterator::DirIterator(DeprecatedString path, Flags flags)
  12. : m_path(move(path))
  13. , m_flags(flags)
  14. {
  15. m_dir = opendir(m_path.characters());
  16. if (!m_dir) {
  17. m_error = Error::from_errno(errno);
  18. }
  19. }
  20. DirIterator::~DirIterator()
  21. {
  22. if (m_dir) {
  23. closedir(m_dir);
  24. m_dir = nullptr;
  25. }
  26. }
  27. DirIterator::DirIterator(DirIterator&& other)
  28. : m_dir(other.m_dir)
  29. , m_error(move(other.m_error))
  30. , m_next(move(other.m_next))
  31. , m_path(move(other.m_path))
  32. , m_flags(other.m_flags)
  33. {
  34. other.m_dir = nullptr;
  35. }
  36. bool DirIterator::advance_next()
  37. {
  38. if (!m_dir)
  39. return false;
  40. while (true) {
  41. errno = 0;
  42. auto* de = readdir(m_dir);
  43. if (!de) {
  44. m_error = Error::from_errno(errno);
  45. m_next.clear();
  46. return false;
  47. }
  48. m_next = DirectoryEntry::from_dirent(*de);
  49. if (m_next->name.is_empty())
  50. return false;
  51. if (m_flags & Flags::SkipDots && m_next->name.starts_with('.'))
  52. continue;
  53. if (m_flags & Flags::SkipParentAndBaseDir && (m_next->name == "." || m_next->name == ".."))
  54. continue;
  55. return !m_next->name.is_empty();
  56. }
  57. }
  58. bool DirIterator::has_next()
  59. {
  60. if (m_next.has_value())
  61. return true;
  62. return advance_next();
  63. }
  64. Optional<DirectoryEntry> DirIterator::next()
  65. {
  66. if (!m_next.has_value())
  67. advance_next();
  68. auto result = m_next;
  69. m_next.clear();
  70. return result;
  71. }
  72. DeprecatedString DirIterator::next_path()
  73. {
  74. auto entry = next();
  75. if (entry.has_value())
  76. return entry->name;
  77. return "";
  78. }
  79. DeprecatedString DirIterator::next_full_path()
  80. {
  81. StringBuilder builder;
  82. builder.append(m_path);
  83. if (!m_path.ends_with('/'))
  84. builder.append('/');
  85. builder.append(next_path());
  86. return builder.to_deprecated_string();
  87. }
  88. int DirIterator::fd() const
  89. {
  90. if (!m_dir)
  91. return -1;
  92. return dirfd(m_dir);
  93. }
  94. }