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 
12 #include "base/base_export.h"
13 #include "base/scoped_generic.h"
14 #include "build/build_config.h"
15 
16 namespace base {
17 
18 namespace internal {
19 
20 #if defined(OS_ANDROID)
21 // Use fdsan on android.
22 struct BASE_EXPORT ScopedFDCloseTraits : public ScopedGenericOwnershipTracking {
InvalidValueScopedFDCloseTraits23   static int InvalidValue() { return -1; }
24   static void Free(int);
25   static void Acquire(const ScopedGeneric<int, ScopedFDCloseTraits>&, int);
26   static void Release(const ScopedGeneric<int, ScopedFDCloseTraits>&, int);
27 };
28 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
29 struct BASE_EXPORT ScopedFDCloseTraits {
30   static int InvalidValue() {
31     return -1;
32   }
33   static void Free(int fd);
34 };
35 #endif
36 
37 // Functor for |ScopedFILE| (below).
38 struct ScopedFILECloser {
operatorScopedFILECloser39   inline void operator()(FILE* x) const {
40     if (x)
41       fclose(x);
42   }
43 };
44 
45 }  // namespace internal
46 
47 // -----------------------------------------------------------------------------
48 
49 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
50 // A low-level Posix file descriptor closer class. Use this when writing
51 // platform-specific code, especially that does non-file-like things with the
52 // FD (like sockets).
53 //
54 // If you're writing low-level Windows code, see base/win/scoped_handle.h
55 // which provides some additional functionality.
56 //
57 // If you're writing cross-platform code that deals with actual files, you
58 // should generally use base::File instead which can be constructed with a
59 // handle, and in addition to handling ownership, has convenient cross-platform
60 // file manipulation functions on it.
61 typedef ScopedGeneric<int, internal::ScopedFDCloseTraits> ScopedFD;
62 #endif
63 
64 // Automatically closes |FILE*|s.
65 typedef std::unique_ptr<FILE, internal::ScopedFILECloser> ScopedFILE;
66 
67 }  // namespace base
68 
69 #endif  // BASE_FILES_SCOPED_FILE_H_
70