summaryrefslogtreecommitdiff
path: root/memtrack-pixel/core/filesystem.cpp
blob: fa25fdcfce9ed322319513e5e9e41c4b75e209e2 (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
68
69
70
#include "filesystem.h"

#include <dirent.h>
#include <log/log.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <sstream>
#include <string>
#include <vector>

namespace filesystem {

bool exists(const path& p) {
    struct stat s;
    return stat(p.string().c_str(), &s) == 0;
}

bool is_directory(const path& p) {
    struct stat s;
    if (stat(p.string().c_str(), &s))
        return false;

    return S_ISDIR(s.st_mode);
}

bool is_symlink(const path& p) {
    struct stat s;
    if (lstat(p.string().c_str(), &s))
        return false;

    return S_ISLNK(s.st_mode);
}

path read_symlink(const path& p) {
    char* actualPath = realpath(p.string().c_str(), NULL);
    if (!actualPath) {
        return path(p.string());
    }

    path out(actualPath);
    free(actualPath);
    return out;
}

std::vector<directory_entry> directory_iterator(const path& p) {
    if (!exists(p) || !is_directory(p))
        return {};

    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(p.string().c_str()), &closedir);
    if (!dir) {
        ALOGE("Failed to open %s directory", p.string().c_str());
    }

    std::vector<directory_entry> out;
    struct dirent* dent;
    while ((dent = readdir(dir.get()))) {
        if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
            continue;

        std::stringstream ss(p.string());
        ss << "/" << dent->d_name;
        out.emplace_back(ss.str());
    }

    return out;
}

} // namespace filesystem