DirIterator.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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. if (errno != 0) {
  45. m_error = Error::from_errno(errno);
  46. dbgln("DirIteration error: {}", m_error.value());
  47. }
  48. m_next.clear();
  49. return false;
  50. }
  51. m_next = DirectoryEntry::from_dirent(*de);
  52. if (m_next->name.is_empty())
  53. return false;
  54. if (m_flags & Flags::SkipDots && m_next->name.starts_with('.'))
  55. continue;
  56. if (m_flags & Flags::SkipParentAndBaseDir && (m_next->name == "." || m_next->name == ".."))
  57. continue;
  58. return !m_next->name.is_empty();
  59. }
  60. }
  61. bool DirIterator::has_next()
  62. {
  63. if (m_next.has_value())
  64. return true;
  65. return advance_next();
  66. }
  67. Optional<DirectoryEntry> DirIterator::next()
  68. {
  69. if (!m_next.has_value())
  70. advance_next();
  71. auto result = m_next;
  72. m_next.clear();
  73. return result;
  74. }
  75. DeprecatedString DirIterator::next_path()
  76. {
  77. auto entry = next();
  78. if (entry.has_value())
  79. return entry->name;
  80. return "";
  81. }
  82. DeprecatedString DirIterator::next_full_path()
  83. {
  84. StringBuilder builder;
  85. builder.append(m_path);
  86. if (!m_path.ends_with('/'))
  87. builder.append('/');
  88. builder.append(next_path());
  89. return builder.to_deprecated_string();
  90. }
  91. int DirIterator::fd() const
  92. {
  93. if (!m_dir)
  94. return -1;
  95. return dirfd(m_dir);
  96. }
  97. }