Debian Codegraph @

inst/include/sourcetools/read/posix/FileConnection.h

raw
1 #ifndef SOURCETOOLS_READ_POSIX_FILE_CONNECTION_H
2 #define SOURCETOOLS_READ_POSIX_FILE_CONNECTION_H
3
4 #include <cstddef>
5
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 #include <unistd.h>
9
10 namespace sourcetools {
11 namespace detail {
12
13 class FileConnection
14 {
15 public:
16
17 typedef int FileDescriptor;
18
19 FileConnection(const char* path, int flags = O_RDONLY)
20 {
21 fd_ = ::open(path, flags);
22 }
23
24 ~FileConnection()
25 {
26 if (open())
27 ::close(fd_);
28 }
29
30 bool open()
31 {
32 return fd_ != -1;
33 }
34
35 bool size(std::size_t* pSize)
36 {
37 struct stat info;
38 if (::fstat(fd_, &info) == -1)
39 return false;
40
41 *pSize = info.st_size;
42 return true;
43 }
44
45 operator FileDescriptor() const
46 {
47 return fd_;
48 }
49
50 private:
51 FileDescriptor fd_;
52 };
53
54
55 } // namespace detail
56 } // namespace sourcetools
57
58 #endif /* SOURCETOOLS_READ_POSIX_FILE_CONNECTION_H */