File::tryOpen
[folly.git] / folly / File.h
1 /*
2  * Copyright 2013 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef FOLLY_FILE_H_
18 #define FOLLY_FILE_H_
19
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <fcntl.h>
23
24 namespace folly {
25
26 /**
27  * A File represents an open file.
28  */
29 class File {
30  public:
31   /**
32    * Creates an empty File object, for late initialization.
33    */
34   File();
35
36   /**
37    * Create a File object from an existing file descriptor.
38    * Takes ownership of the file descriptor if ownsFd is true.
39    */
40   /* implicit */ File(int fd,
41                       bool ownsFd = false);
42
43   /**
44    * Open and create a file object.  Throws on error.
45    */
46   /* implicit */ File(const char* name,
47                       int flags = O_RDONLY,
48                       mode_t mode = 0644);
49
50   ~File();
51
52   /**
53    * Create and return a temporary, owned file (uses tmpfile()).
54    */
55   static File temporary();
56
57   /**
58    * Attempts to open the file at the given path.  Returns an 'closed` File
59    * instance on failure, which will evaluate to false.
60    */
61   static File tryOpen(const char* name,
62                       int flags = O_RDONLY,
63                       mode_t mode = 0644);
64
65   /**
66    * Return the file descriptor, or -1 if the file was closed.
67    */
68   int fd() const { return fd_; }
69
70   /**
71    * Returns 'true' iff the file was successfully opened.
72    */
73   explicit operator bool() const {
74     return fd_ >= 0;
75   }
76
77   /**
78    * If we own the file descriptor, close the file and throw on error.
79    * Otherwise, do nothing.
80    */
81   void close();
82
83   /**
84    * Closes the file (if owned).  Returns true on success, false (and sets
85    * errno) on error.
86    */
87   bool closeNoThrow();
88
89   /**
90    * Releases the file descriptor; no longer owned by this File.
91    */
92   void release();
93
94   /**
95    * Swap this File with another.
96    */
97   void swap(File& other);
98
99   // movable
100   File(File&&);
101   File& operator=(File&&);
102
103  private:
104   // unique
105   File(const File&) = delete;
106   File& operator=(const File&) = delete;
107
108   int fd_;
109   bool ownsFd_;
110 };
111
112 void swap(File& a, File& b);
113
114 }  // namespace folly
115
116 #endif /* FOLLY_FILE_H_ */