|
1 // Copyright (c) 2006-2008 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. |
|
4 |
|
5 #include "base/platform_file.h" |
|
6 |
|
7 #include <sys/stat.h> |
|
8 #include <fcntl.h> |
|
9 #include <errno.h> |
|
10 #ifdef ANDROID |
|
11 #include <linux/stat.h> |
|
12 #endif |
|
13 |
|
14 #include "base/logging.h" |
|
15 #include "base/string_util.h" |
|
16 |
|
17 namespace base { |
|
18 |
|
19 // TODO(erikkay): does it make sense to support PLATFORM_FILE_EXCLUSIVE_* here? |
|
20 PlatformFile CreatePlatformFile(const std::wstring& name, |
|
21 int flags, |
|
22 bool* created) { |
|
23 int open_flags = 0; |
|
24 if (flags & PLATFORM_FILE_CREATE) |
|
25 open_flags = O_CREAT | O_EXCL; |
|
26 |
|
27 if (flags & PLATFORM_FILE_CREATE_ALWAYS) { |
|
28 DCHECK(!open_flags); |
|
29 open_flags = O_CREAT | O_TRUNC; |
|
30 } |
|
31 |
|
32 if (!open_flags && !(flags & PLATFORM_FILE_OPEN) && |
|
33 !(flags & PLATFORM_FILE_OPEN_ALWAYS)) { |
|
34 NOTREACHED(); |
|
35 errno = ENOTSUP; |
|
36 return kInvalidPlatformFileValue; |
|
37 } |
|
38 |
|
39 if (flags & PLATFORM_FILE_WRITE && flags & PLATFORM_FILE_READ) { |
|
40 open_flags |= O_RDWR; |
|
41 } else if (flags & PLATFORM_FILE_WRITE) { |
|
42 open_flags |= O_WRONLY; |
|
43 } else if (!(flags & PLATFORM_FILE_READ)) { |
|
44 NOTREACHED(); |
|
45 } |
|
46 |
|
47 DCHECK(O_RDONLY == 0); |
|
48 |
|
49 int descriptor = open(WideToUTF8(name).c_str(), open_flags, |
|
50 S_IRUSR | S_IWUSR); |
|
51 |
|
52 if (flags & PLATFORM_FILE_OPEN_ALWAYS) { |
|
53 if (descriptor > 0) { |
|
54 if (created) |
|
55 *created = false; |
|
56 } else { |
|
57 open_flags |= O_CREAT; |
|
58 descriptor = open(WideToUTF8(name).c_str(), open_flags, |
|
59 S_IRUSR | S_IWUSR); |
|
60 if (created && descriptor > 0) |
|
61 *created = true; |
|
62 } |
|
63 } |
|
64 |
|
65 return descriptor; |
|
66 } |
|
67 |
|
68 } // namespace base |