rAc - revert invalid suggestions to edit mode
[chromium-blink-merge.git] / base / files / file.h
blob8597473cc7a47ea381ce08c5b7646ea35524fa83
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_FILES_FILE_H_
6 #define BASE_FILES_FILE_H_
8 #include "build/build_config.h"
9 #if defined(OS_WIN)
10 #include <windows.h>
11 #endif
13 #include <string>
15 #include "base/base_export.h"
16 #include "base/basictypes.h"
17 #include "base/files/file_path.h"
18 #include "base/move.h"
19 #include "base/time/time.h"
21 #if defined(OS_WIN)
22 #include "base/win/scoped_handle.h"
23 #endif
25 namespace base {
27 #if defined(OS_WIN)
28 typedef HANDLE PlatformFile;
29 #elif defined(OS_POSIX)
30 typedef int PlatformFile;
31 #endif
34 // Thin wrapper around an OS-level file.
35 // Note that this class does not provide any support for asynchronous IO, other
36 // than the ability to create asynchronous handles on Windows.
38 // Note about const: this class does not attempt to determine if the underlying
39 // file system object is affected by a particular method in order to consider
40 // that method const or not. Only methods that deal with member variables in an
41 // obvious non-modifying way are marked as const. Any method that forward calls
42 // to the OS is not considered const, even if there is no apparent change to
43 // member variables.
44 class BASE_EXPORT File {
45 MOVE_ONLY_TYPE_FOR_CPP_03(File, RValue)
47 public:
48 // FLAG_(OPEN|CREATE).* are mutually exclusive. You should specify exactly one
49 // of the five (possibly combining with other flags) when opening or creating
50 // a file.
51 // FLAG_(WRITE|APPEND) are mutually exclusive. This is so that APPEND behavior
52 // will be consistent with O_APPEND on POSIX.
53 // FLAG_EXCLUSIVE_(READ|WRITE) only grant exclusive access to the file on
54 // creation on POSIX; for existing files, consider using Lock().
55 enum Flags {
56 FLAG_OPEN = 1 << 0, // Opens a file, only if it exists.
57 FLAG_CREATE = 1 << 1, // Creates a new file, only if it does not
58 // already exist.
59 FLAG_OPEN_ALWAYS = 1 << 2, // May create a new file.
60 FLAG_CREATE_ALWAYS = 1 << 3, // May overwrite an old file.
61 FLAG_OPEN_TRUNCATED = 1 << 4, // Opens a file and truncates it, only if it
62 // exists.
63 FLAG_READ = 1 << 5,
64 FLAG_WRITE = 1 << 6,
65 FLAG_APPEND = 1 << 7,
66 FLAG_EXCLUSIVE_READ = 1 << 8, // EXCLUSIVE is opposite of Windows SHARE.
67 FLAG_EXCLUSIVE_WRITE = 1 << 9,
68 FLAG_ASYNC = 1 << 10,
69 FLAG_TEMPORARY = 1 << 11, // Used on Windows only.
70 FLAG_HIDDEN = 1 << 12, // Used on Windows only.
71 FLAG_DELETE_ON_CLOSE = 1 << 13,
72 FLAG_WRITE_ATTRIBUTES = 1 << 14, // Used on Windows only.
73 FLAG_SHARE_DELETE = 1 << 15, // Used on Windows only.
74 FLAG_TERMINAL_DEVICE = 1 << 16, // Serial port flags.
75 FLAG_BACKUP_SEMANTICS = 1 << 17, // Used on Windows only.
76 FLAG_EXECUTE = 1 << 18, // Used on Windows only.
79 // This enum has been recorded in multiple histograms. If the order of the
80 // fields needs to change, please ensure that those histograms are obsolete or
81 // have been moved to a different enum.
83 // FILE_ERROR_ACCESS_DENIED is returned when a call fails because of a
84 // filesystem restriction. FILE_ERROR_SECURITY is returned when a browser
85 // policy doesn't allow the operation to be executed.
86 enum Error {
87 FILE_OK = 0,
88 FILE_ERROR_FAILED = -1,
89 FILE_ERROR_IN_USE = -2,
90 FILE_ERROR_EXISTS = -3,
91 FILE_ERROR_NOT_FOUND = -4,
92 FILE_ERROR_ACCESS_DENIED = -5,
93 FILE_ERROR_TOO_MANY_OPENED = -6,
94 FILE_ERROR_NO_MEMORY = -7,
95 FILE_ERROR_NO_SPACE = -8,
96 FILE_ERROR_NOT_A_DIRECTORY = -9,
97 FILE_ERROR_INVALID_OPERATION = -10,
98 FILE_ERROR_SECURITY = -11,
99 FILE_ERROR_ABORT = -12,
100 FILE_ERROR_NOT_A_FILE = -13,
101 FILE_ERROR_NOT_EMPTY = -14,
102 FILE_ERROR_INVALID_URL = -15,
103 FILE_ERROR_IO = -16,
104 // Put new entries here and increment FILE_ERROR_MAX.
105 FILE_ERROR_MAX = -17
108 // This explicit mapping matches both FILE_ on Windows and SEEK_ on Linux.
109 enum Whence {
110 FROM_BEGIN = 0,
111 FROM_CURRENT = 1,
112 FROM_END = 2
115 // Used to hold information about a given file.
116 // If you add more fields to this structure (platform-specific fields are OK),
117 // make sure to update all functions that use it in file_util_{win|posix}.cc
118 // too, and the ParamTraits<base::PlatformFileInfo> implementation in
119 // chrome/common/common_param_traits.cc.
120 struct BASE_EXPORT Info {
121 Info();
122 ~Info();
124 // The size of the file in bytes. Undefined when is_directory is true.
125 int64 size;
127 // True if the file corresponds to a directory.
128 bool is_directory;
130 // True if the file corresponds to a symbolic link.
131 bool is_symbolic_link;
133 // The last modified time of a file.
134 base::Time last_modified;
136 // The last accessed time of a file.
137 base::Time last_accessed;
139 // The creation time of a file.
140 base::Time creation_time;
143 File();
145 // Creates or opens the given file. This will fail with 'access denied' if the
146 // |name| contains path traversal ('..') components.
147 File(const FilePath& name, uint32 flags);
149 // Takes ownership of |platform_file|.
150 explicit File(PlatformFile platform_file);
152 // Move constructor for C++03 move emulation of this type.
153 File(RValue other);
155 ~File();
157 // Move operator= for C++03 move emulation of this type.
158 File& operator=(RValue other);
160 // Creates or opens the given file.
161 void Initialize(const FilePath& name, uint32 flags);
163 // Creates or opens the given file, allowing paths with traversal ('..')
164 // components. Use only with extreme care.
165 void InitializeUnsafe(const FilePath& name, uint32 flags);
167 bool IsValid() const;
169 // Returns true if a new file was created (or an old one truncated to zero
170 // length to simulate a new file, which can happen with
171 // FLAG_CREATE_ALWAYS), and false otherwise.
172 bool created() const { return created_; }
174 // Returns the OS result of opening this file. Note that the way to verify
175 // the success of the operation is to use IsValid(), not this method:
176 // File file(name, flags);
177 // if (!file.IsValid())
178 // return;
179 Error error_details() const { return error_details_; }
181 PlatformFile GetPlatformFile() const { return file_; }
182 PlatformFile TakePlatformFile();
184 // Destroying this object closes the file automatically.
185 void Close();
187 // Changes current position in the file to an |offset| relative to an origin
188 // defined by |whence|. Returns the resultant current position in the file
189 // (relative to the start) or -1 in case of error.
190 int64 Seek(Whence whence, int64 offset);
192 // Reads the given number of bytes (or until EOF is reached) starting with the
193 // given offset. Returns the number of bytes read, or -1 on error. Note that
194 // this function makes a best effort to read all data on all platforms, so it
195 // is not intended for stream oriented files but instead for cases when the
196 // normal expectation is that actually |size| bytes are read unless there is
197 // an error.
198 int Read(int64 offset, char* data, int size);
200 // Same as above but without seek.
201 int ReadAtCurrentPos(char* data, int size);
203 // Reads the given number of bytes (or until EOF is reached) starting with the
204 // given offset, but does not make any effort to read all data on all
205 // platforms. Returns the number of bytes read, or -1 on error.
206 int ReadNoBestEffort(int64 offset, char* data, int size);
208 // Same as above but without seek.
209 int ReadAtCurrentPosNoBestEffort(char* data, int size);
211 // Writes the given buffer into the file at the given offset, overwritting any
212 // data that was previously there. Returns the number of bytes written, or -1
213 // on error. Note that this function makes a best effort to write all data on
214 // all platforms.
215 // Ignores the offset and writes to the end of the file if the file was opened
216 // with FLAG_APPEND.
217 int Write(int64 offset, const char* data, int size);
219 // Save as above but without seek.
220 int WriteAtCurrentPos(const char* data, int size);
222 // Save as above but does not make any effort to write all data on all
223 // platforms. Returns the number of bytes written, or -1 on error.
224 int WriteAtCurrentPosNoBestEffort(const char* data, int size);
226 // Returns the current size of this file, or a negative number on failure.
227 int64 GetLength();
229 // Truncates the file to the given length. If |length| is greater than the
230 // current size of the file, the file is extended with zeros. If the file
231 // doesn't exist, |false| is returned.
232 bool SetLength(int64 length);
234 // Flushes the buffers.
235 bool Flush();
237 // Updates the file times.
238 bool SetTimes(Time last_access_time, Time last_modified_time);
240 // Returns some basic information for the given file.
241 bool GetInfo(Info* info);
243 // Attempts to take an exclusive write lock on the file. Returns immediately
244 // (i.e. does not wait for another process to unlock the file). If the lock
245 // was obtained, the result will be FILE_OK. A lock only guarantees
246 // that other processes may not also take a lock on the same file with the
247 // same API - it may still be opened, renamed, unlinked, etc.
249 // Common semantics:
250 // * Locks are held by processes, but not inherited by child processes.
251 // * Locks are released by the OS on file close or process termination.
252 // * Locks are reliable only on local filesystems.
253 // * Duplicated file handles may also write to locked files.
254 // Windows-specific semantics:
255 // * Locks are mandatory for read/write APIs, advisory for mapping APIs.
256 // * Within a process, locking the same file (by the same or new handle)
257 // will fail.
258 // POSIX-specific semantics:
259 // * Locks are advisory only.
260 // * Within a process, locking the same file (by the same or new handle)
261 // will succeed.
262 // * Closing any descriptor on a given file releases the lock.
263 Error Lock();
265 // Unlock a file previously locked.
266 Error Unlock();
268 #if defined(OS_WIN)
269 static Error OSErrorToFileError(DWORD last_error);
270 #elif defined(OS_POSIX)
271 static Error OSErrorToFileError(int saved_errno);
272 #endif
274 private:
275 void SetPlatformFile(PlatformFile file);
277 #if defined(OS_WIN)
278 win::ScopedHandle file_;
279 #elif defined(OS_POSIX)
280 PlatformFile file_;
281 #endif
283 Error error_details_;
284 bool created_;
285 bool async_;
288 } // namespace base
290 #endif // BASE_FILES_FILE_H_