DirIterator.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Vector.h>
  7. #include <LibCore/DirIterator.h>
  8. #include <errno.h>
  9. #include <unistd.h>
  10. namespace Core {
  11. DirIterator::DirIterator(String 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 = errno;
  18. }
  19. }
  20. DirIterator::~DirIterator()
  21. {
  22. if (m_dir) {
  23. closedir(m_dir);
  24. m_dir = nullptr;
  25. }
  26. }
  27. bool DirIterator::advance_next()
  28. {
  29. if (!m_dir)
  30. return false;
  31. while (true) {
  32. errno = 0;
  33. auto* de = readdir(m_dir);
  34. if (!de) {
  35. m_error = errno;
  36. m_next = String();
  37. return false;
  38. }
  39. m_next = de->d_name;
  40. if (m_next.is_null())
  41. return false;
  42. if (m_flags & Flags::SkipDots && m_next.starts_with('.'))
  43. continue;
  44. if (m_flags & Flags::SkipParentAndBaseDir && (m_next == "." || m_next == ".."))
  45. continue;
  46. return !m_next.is_empty();
  47. }
  48. }
  49. bool DirIterator::has_next()
  50. {
  51. if (!m_next.is_null())
  52. return true;
  53. return advance_next();
  54. }
  55. String DirIterator::next_path()
  56. {
  57. if (m_next.is_null())
  58. advance_next();
  59. auto tmp = m_next;
  60. m_next = String();
  61. return tmp;
  62. }
  63. String DirIterator::next_full_path()
  64. {
  65. return String::formatted("{}/{}", m_path, next_path());
  66. }
  67. String find_executable_in_path(String filename)
  68. {
  69. if (filename.starts_with('/')) {
  70. if (access(filename.characters(), X_OK) == 0)
  71. return filename;
  72. return {};
  73. }
  74. for (auto directory : String { getenv("PATH") }.split(':')) {
  75. auto fullpath = String::formatted("{}/{}", directory, filename);
  76. if (access(fullpath.characters(), X_OK) == 0)
  77. return fullpath;
  78. }
  79. return {};
  80. }
  81. int DirIterator::fd() const
  82. {
  83. if (!m_dir)
  84. return -1;
  85. return dirfd(m_dir);
  86. }
  87. }