platform_file_posix.cc revision c7f5f8508d98d5952d42ed7648c2a8f30a4da156
1// Copyright (c) 2009 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 <fcntl.h> 8#include <errno.h> 9#include <sys/stat.h> 10 11#include "base/file_path.h" 12#include "base/logging.h" 13#include "base/utf_string_conversions.h" 14 15namespace base { 16 17// TODO(erikkay): does it make sense to support PLATFORM_FILE_EXCLUSIVE_* here? 18PlatformFile CreatePlatformFile(const FilePath& name, int flags, 19 bool* created) { 20 int open_flags = 0; 21 if (flags & PLATFORM_FILE_CREATE) 22 open_flags = O_CREAT | O_EXCL; 23 24 if (flags & PLATFORM_FILE_CREATE_ALWAYS) { 25 DCHECK(!open_flags); 26 open_flags = O_CREAT | O_TRUNC; 27 } 28 29 if (!open_flags && !(flags & PLATFORM_FILE_OPEN) && 30 !(flags & PLATFORM_FILE_OPEN_ALWAYS)) { 31 NOTREACHED(); 32 errno = EOPNOTSUPP; 33 return kInvalidPlatformFileValue; 34 } 35 36 if (flags & PLATFORM_FILE_WRITE && flags & PLATFORM_FILE_READ) { 37 open_flags |= O_RDWR; 38 } else if (flags & PLATFORM_FILE_WRITE) { 39 open_flags |= O_WRONLY; 40 } else if (!(flags & PLATFORM_FILE_READ)) { 41 NOTREACHED(); 42 } 43 44 DCHECK(O_RDONLY == 0); 45 46 int descriptor = open(name.value().c_str(), open_flags, S_IRUSR | S_IWUSR); 47 48 if (flags & PLATFORM_FILE_OPEN_ALWAYS) { 49 if (descriptor > 0) { 50 if (created) 51 *created = false; 52 } else { 53 open_flags |= O_CREAT; 54 if (flags & PLATFORM_FILE_EXCLUSIVE_READ || 55 flags & PLATFORM_FILE_EXCLUSIVE_WRITE) { 56 open_flags |= O_EXCL; // together with O_CREAT implies O_NOFOLLOW 57 } 58 descriptor = open(name.value().c_str(), open_flags, S_IRUSR | S_IWUSR); 59 if (created && descriptor > 0) 60 *created = true; 61 } 62 } 63 64 if ((descriptor > 0) && (flags & PLATFORM_FILE_DELETE_ON_CLOSE)) { 65 unlink(name.value().c_str()); 66 } 67 68 return descriptor; 69} 70 71PlatformFile CreatePlatformFile(const std::wstring& name, int flags, 72 bool* created) { 73 return CreatePlatformFile(FilePath::FromWStringHack(name), flags, created); 74} 75 76bool ClosePlatformFile(PlatformFile file) { 77 return close(file); 78} 79 80} // namespace base 81