blob: 5be4c4bb7b85df74751c53cf1c8c05d53067bf70 [file] [log] [blame]
Matt Spinleree7adb72017-08-21 15:17:19 -05001#pragma once
2
3#include <unistd.h>
4namespace witherspoon
5{
6namespace power
7{
8namespace util
9{
10
11/**
12 * @class FileDescriptor
13 *
14 * Closes the file descriptor on destruction
15 */
16class FileDescriptor
17{
18 public:
19
20 FileDescriptor() = default;
21 FileDescriptor(const FileDescriptor&) = delete;
22 FileDescriptor& operator=(const FileDescriptor&) = delete;
23 FileDescriptor(FileDescriptor&&) = delete;
24 FileDescriptor& operator=(FileDescriptor&&) = delete;
25
26 /**
27 * Constructor
28 *
29 * @param[in] fd - File descriptor
30 */
31 FileDescriptor(int fd) : fd(fd)
32 {
33 }
34
35 ~FileDescriptor()
36 {
37 if (fd >= 0)
38 {
39 close(fd);
40 }
41 }
42
43 int operator()()
44 {
45 return fd;
46 }
47
48 operator bool() const
49 {
50 return fd != -1;
51 }
52
53 void set(int descriptor)
54 {
55 if (fd >= 0)
56 {
57 close(fd);
58 }
59
60 fd = descriptor;
61 }
62
63 private:
64
65 /**
66 * File descriptor
67 */
68 int fd = -1;
69};
70
71}
72}
73}