blob: 7d7ecc5578c74da77dc9ff3db08c9a1350866e21 [file] [log] [blame]
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08001#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
12namespace android {
13namespace dvr {
14
15// Utility class around readdir() that handles automatic cleanup.
16class DirectoryReader {
17 public:
18 explicit DirectoryReader(base::unique_fd directory_fd) {
19 directory_ = fdopendir(directory_fd.get());
20 error_ = errno;
21 if (directory_ != nullptr)
22 directory_fd.release();
23 }
24
25 ~DirectoryReader() {
26 if (directory_)
27 closedir(directory_);
28 }
29
30 bool IsValid() const { return directory_ != nullptr; }
31 explicit operator bool() const { return IsValid(); }
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.
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_