1 #ifndef ANDROID_DVR_PERFORMANCED_DIRECTORY_READER_H_
2 #define ANDROID_DVR_PERFORMANCED_DIRECTORY_READER_H_
3 
4 #include <dirent.h>
5 #include <errno.h>
6 #include <fcntl.h>
7 #include <sys/stat.h>
8 #include <sys/types.h>
9 
10 #include <android-base/unique_fd.h>
11 
12 namespace android {
13 namespace dvr {
14 
15 // Utility class around readdir() that handles automatic cleanup.
16 class DirectoryReader {
17  public:
DirectoryReader(base::unique_fd directory_fd)18   explicit DirectoryReader(base::unique_fd directory_fd) {
19     int fd = directory_fd.release();
20     directory_ = fdopendir(fd);
21     error_ = errno;
22     if (directory_ == nullptr)
23       close(fd);
24   }
25 
~DirectoryReader()26   ~DirectoryReader() {
27     if (directory_)
28       closedir(directory_);
29   }
30 
IsValid()31   bool IsValid() const { return directory_ != nullptr; }
32   explicit operator bool() const { return IsValid(); }
GetError()33   int GetError() const { return error_; }
34 
35   // Returns a pointer to a dirent describing the next directory entry. The
36   // pointer is only valid unitl the next call to Next() or the DirectoryReader
37   // is destroyed. Returns nullptr when the end of the directory is reached.
Next()38   dirent* Next() {
39     if (directory_)
40       return readdir(directory_);
41     else
42       return nullptr;
43   }
44 
45  private:
46   DIR* directory_;
47   int error_;
48 
49   DirectoryReader(const DirectoryReader&) = delete;
50   void operator=(const DirectoryReader&) = delete;
51 };
52 
53 }  // namespace dvr
54 }  // namespace android
55 
56 #endif  // ANDROID_DVR_PERFORMANCED_DIRECTORY_READER_H_
57