Remove 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    * Return the file descriptor, or -1 if the file was closed.
59    */
60   int fd() const { return fd_; }
61
62   /**
63    * Returns 'true' iff the file was successfully opened.
64    */
65   explicit operator bool() const {
66     return fd_ >= 0;
67   }
68
69   /**
70    * If we own the file descriptor, close the file and throw on error.
71    * Otherwise, do nothing.
72    */
73   void close();
74
75   /**
76    * Closes the file (if owned).  Returns true on success, false (and sets
77    * errno) on error.
78    */
79   bool closeNoThrow();
80
81   /**
82    * Releases the file descriptor; no longer owned by this File.
83    */
84   void release();
85
86   /**
87    * Swap this File with another.
88    */
89   void swap(File& other);
90
91   // movable
92   File(File&&);
93   File& operator=(File&&);
94
95  private:
96   // unique
97   File(const File&) = delete;
98   File& operator=(const File&) = delete;
99
100   int fd_;
101   bool ownsFd_;
102 };
103
104 void swap(File& a, File& b);
105
106 }  // namespace folly
107
108 #endif /* FOLLY_FILE_H_ */