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