Scott Graham | 6696211 | 2018-06-08 12:42:08 -0700 | [diff] [blame] | 1 | // Copyright 2014 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 | #ifndef BASE_FILES_SCOPED_FILE_H_ |
| 6 | #define BASE_FILES_SCOPED_FILE_H_ |
| 7 | |
| 8 | #include <stdio.h> |
| 9 | |
| 10 | #include <memory> |
| 11 | |
Scott Graham | 6696211 | 2018-06-08 12:42:08 -0700 | [diff] [blame] | 12 | #include "base/logging.h" |
| 13 | #include "base/scoped_generic.h" |
Scott Graham | 76a8dc7 | 2018-06-18 13:37:29 -0700 | [diff] [blame] | 14 | #include "util/build_config.h" |
Scott Graham | 6696211 | 2018-06-08 12:42:08 -0700 | [diff] [blame] | 15 | |
| 16 | namespace base { |
| 17 | |
| 18 | namespace internal { |
| 19 | |
| 20 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
Scott Graham | 4459807 | 2018-06-14 22:01:37 -0700 | [diff] [blame] | 21 | struct ScopedFDCloseTraits { |
Scott Graham | 98cd3ca | 2018-06-14 22:26:55 -0700 | [diff] [blame] | 22 | static int InvalidValue() { return -1; } |
Scott Graham | 6696211 | 2018-06-08 12:42:08 -0700 | [diff] [blame] | 23 | static void Free(int fd); |
| 24 | }; |
| 25 | #endif |
| 26 | |
| 27 | // Functor for |ScopedFILE| (below). |
| 28 | struct ScopedFILECloser { |
| 29 | inline void operator()(FILE* x) const { |
| 30 | if (x) |
| 31 | fclose(x); |
| 32 | } |
| 33 | }; |
| 34 | |
| 35 | } // namespace internal |
| 36 | |
| 37 | // ----------------------------------------------------------------------------- |
| 38 | |
| 39 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 40 | // A low-level Posix file descriptor closer class. Use this when writing |
| 41 | // platform-specific code, especially that does non-file-like things with the |
| 42 | // FD (like sockets). |
| 43 | // |
| 44 | // If you're writing low-level Windows code, see base/win/scoped_handle.h |
| 45 | // which provides some additional functionality. |
| 46 | // |
| 47 | // If you're writing cross-platform code that deals with actual files, you |
| 48 | // should generally use base::File instead which can be constructed with a |
| 49 | // handle, and in addition to handling ownership, has convenient cross-platform |
| 50 | // file manipulation functions on it. |
| 51 | typedef ScopedGeneric<int, internal::ScopedFDCloseTraits> ScopedFD; |
| 52 | #endif |
| 53 | |
| 54 | // Automatically closes |FILE*|s. |
| 55 | typedef std::unique_ptr<FILE, internal::ScopedFILECloser> ScopedFILE; |
| 56 | |
| 57 | } // namespace base |
| 58 | |
| 59 | #endif // BASE_FILES_SCOPED_FILE_H_ |