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