blob: 0d896504300e7e1bb8cae4275ccc38e4066aa339 [file] [log] [blame]
Scott Graham66962112018-06-08 12:42:08 -07001// 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 Graham66962112018-06-08 12:42:08 -070012#include "base/logging.h"
13#include "base/scoped_generic.h"
Scott Graham76a8dc72018-06-18 13:37:29 -070014#include "util/build_config.h"
Scott Graham66962112018-06-08 12:42:08 -070015
16namespace base {
17
18namespace internal {
19
20#if defined(OS_POSIX) || defined(OS_FUCHSIA)
Scott Graham44598072018-06-14 22:01:37 -070021struct ScopedFDCloseTraits {
Scott Graham98cd3ca2018-06-14 22:26:55 -070022 static int InvalidValue() { return -1; }
Scott Graham66962112018-06-08 12:42:08 -070023 static void Free(int fd);
24};
25#endif
26
27// Functor for |ScopedFILE| (below).
28struct 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.
51typedef ScopedGeneric<int, internal::ScopedFDCloseTraits> ScopedFD;
52#endif
53
54// Automatically closes |FILE*|s.
55typedef std::unique_ptr<FILE, internal::ScopedFILECloser> ScopedFILE;
56
57} // namespace base
58
59#endif // BASE_FILES_SCOPED_FILE_H_