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 directory_ = fdopendir(directory_fd.get()); 20 error_ = errno; 21 if (directory_ != nullptr) 22 (void) directory_fd.release(); // ignore return result? 23 } 24 ~DirectoryReader()25 ~DirectoryReader() { 26 if (directory_) 27 closedir(directory_); 28 } 29 IsValid()30 bool IsValid() const { return directory_ != nullptr; } 31 explicit operator bool() const { return IsValid(); } GetError()32 int GetError() const { return error_; } 33 34 // Returns a pointer to a dirent describing the next directory entry. The 35 // pointer is only valid unitl the next call to Next() or the DirectoryReader 36 // is destroyed. Returns nullptr when the end of the directory is reached. Next()37 dirent* Next() { 38 if (directory_) 39 return readdir(directory_); 40 else 41 return nullptr; 42 } 43 44 private: 45 DIR* directory_; 46 int error_; 47 48 DirectoryReader(const DirectoryReader&) = delete; 49 void operator=(const DirectoryReader&) = delete; 50 }; 51 52 } // namespace dvr 53 } // namespace android 54 55 #endif // ANDROID_DVR_PERFORMANCED_DIRECTORY_READER_H_ 56