blob: 7f60d4db9626019268a7146d2da6b2ac1d610734 [file] [log] [blame]
Adam Lesinski282e1812014-01-23 18:17:42 -08001//
2// Copyright 2011 The Android Open Source Project
3//
4// Defines an abstraction for opening a directory on the filesystem and
5// iterating through it.
6
7#ifndef DIRECTORYWALKER_H
8#define DIRECTORYWALKER_H
9
Tomasz Wasilczyk804e8192023-08-23 02:22:53 +000010#include <androidfw/PathUtils.h>
Adam Lesinski282e1812014-01-23 18:17:42 -080011#include <dirent.h>
12#include <sys/types.h>
13#include <sys/param.h>
14#include <sys/stat.h>
15#include <unistd.h>
16#include <utils/String8.h>
17
18#include <stdio.h>
19
20using namespace android;
21
22// Directory Walker
23// This is an abstraction for walking through a directory and getting files
24// and descriptions.
25
26class DirectoryWalker {
27public:
28 virtual ~DirectoryWalker() {};
29 virtual bool openDir(String8 path) = 0;
30 virtual bool openDir(const char* path) = 0;
31 // Advance to next directory entry
32 virtual struct dirent* nextEntry() = 0;
33 // Get the stats for the current entry
34 virtual struct stat* entryStats() = 0;
35 // Clean Up
36 virtual void closeDir() = 0;
37 // This class is able to replicate itself on the heap
38 virtual DirectoryWalker* clone() = 0;
39
40 // DATA MEMBERS
41 // Current directory entry
42 struct dirent mEntry;
43 // Stats for that directory entry
44 struct stat mStats;
45 // Base path
46 String8 mBasePath;
47};
48
49// System Directory Walker
50// This is an implementation of the above abstraction that calls
51// real system calls and is fully functional.
52// functions are inlined since they're very short and simple
53
54class SystemDirectoryWalker : public DirectoryWalker {
55
56 // Default constructor, copy constructor, and destructor are fine
57public:
58 virtual bool openDir(String8 path) {
59 mBasePath = path;
60 dir = NULL;
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +000061 dir = opendir(mBasePath.c_str() );
Adam Lesinski282e1812014-01-23 18:17:42 -080062
63 if (dir == NULL)
64 return false;
65
66 return true;
67 };
68 virtual bool openDir(const char* path) {
69 String8 p(path);
70 openDir(p);
71 return true;
72 };
73 // Advance to next directory entry
74 virtual struct dirent* nextEntry() {
75 struct dirent* entryPtr = readdir(dir);
76 if (entryPtr == NULL)
77 return NULL;
78
79 mEntry = *entryPtr;
80 // Get stats
Tomasz Wasilczyk804e8192023-08-23 02:22:53 +000081 String8 fullPath = appendPathCopy(mBasePath, mEntry.d_name);
Tomasz Wasilczykd2a69832023-08-10 23:54:44 +000082 stat(fullPath.c_str(),&mStats);
Adam Lesinski282e1812014-01-23 18:17:42 -080083 return &mEntry;
84 };
85 // Get the stats for the current entry
86 virtual struct stat* entryStats() {
87 return &mStats;
88 };
89 virtual void closeDir() {
90 closedir(dir);
91 };
92 virtual DirectoryWalker* clone() {
93 return new SystemDirectoryWalker(*this);
94 };
95private:
96 DIR* dir;
97};
98
99#endif // DIRECTORYWALKER_H