• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/logging.h"
13 #include "base/scoped_generic.h"
14 #include "util/build_config.h"
15 
16 namespace base {
17 
18 namespace internal {
19 
20 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
21 struct ScopedFDCloseTraits {
InvalidValueScopedFDCloseTraits22   static int InvalidValue() { return -1; }
23   static void Free(int fd);
24 };
25 #endif
26 
27 // Functor for |ScopedFILE| (below).
28 struct ScopedFILECloser {
operatorScopedFILECloser29   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_
60