summaryrefslogtreecommitdiff
path: root/LibCore/CDirIterator.cpp
blob: aa64ea8b719564db5ca1f3ed9f2ca4e2af00d16e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "CDirIterator.h"
#include <cerrno>

CDirIterator::CDirIterator(const String& path, Flags flags)
    : m_flags(flags)
{
    m_dir = opendir(path.characters());
    if (m_dir == nullptr) {
        m_error = errno;
    }
}

CDirIterator::~CDirIterator()
{
    if (m_dir != nullptr) {
        closedir(m_dir);
        m_dir = nullptr;
    }
}

bool CDirIterator::advance_next()
{
    if (m_dir == nullptr)
        return false;

    bool keep_advancing = true;
    while (keep_advancing) {
        errno = 0;
        auto* de = readdir(m_dir);
        if (de) {
            m_next = de->d_name;
        } else {
            m_error = errno;
            m_next = String();
        }

        if (m_next.is_null()) {
            keep_advancing = false;
        } else if (m_flags & Flags::SkipDots) {
            if (m_next.length() < 1 || m_next[0] != '.') {
                keep_advancing = false;
            }
        } else {
            keep_advancing = false;
        }
    }

    return m_next.length() > 0;
}

bool CDirIterator::has_next()
{
    if (!m_next.is_null())
        return true;

    return advance_next();
}

String CDirIterator::next_path()
{
    if (m_next.is_null())
        advance_next();

    auto tmp = m_next;
    m_next = String();
    return tmp;
}