DirIterator.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. StringBuilder builder;
  66. builder.append(m_path);
  67. if (!m_path.ends_with('/'))
  68. builder.append('/');
  69. builder.append(next_path());
  70. return builder.to_string();
  71. }
  72. String find_executable_in_path(String filename)
  73. {
  74. if (filename.starts_with('/')) {
  75. if (access(filename.characters(), X_OK) == 0)
  76. return filename;
  77. return {};
  78. }
  79. for (auto directory : String { getenv("PATH") }.split(':')) {
  80. auto fullpath = String::formatted("{}/{}", directory, filename);
  81. if (access(fullpath.characters(), X_OK) == 0)
  82. return fullpath;
  83. }
  84. return {};
  85. }
  86. int DirIterator::fd() const
  87. {
  88. if (!m_dir)
  89. return -1;
  90. return dirfd(m_dir);
  91. }
  92. }