ada-lang.c: Rename gnat_encoded_fixed_type_info
[binutils-gdb.git] / gdbsupport / scoped_fd.h
blobec654df5246b6e9ddfc4619c3cb940ab33696146
1 /* scoped_fd, automatically close a file descriptor
3 Copyright (C) 2018-2020 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #ifndef COMMON_SCOPED_FD_H
21 #define COMMON_SCOPED_FD_H
23 #include <unistd.h>
24 #include "filestuff.h"
26 /* A smart-pointer-like class to automatically close a file descriptor. */
28 class scoped_fd
30 public:
31 explicit scoped_fd (int fd = -1) noexcept : m_fd (fd) {}
33 scoped_fd (scoped_fd &&other) noexcept
34 : m_fd (other.m_fd)
36 other.m_fd = -1;
39 ~scoped_fd ()
41 if (m_fd >= 0)
42 close (m_fd);
45 scoped_fd &operator= (scoped_fd &&other)
47 if (m_fd != other.m_fd)
49 if (m_fd >= 0)
50 close (m_fd);
51 m_fd = other.m_fd;
52 other.m_fd = -1;
54 return *this;
57 DISABLE_COPY_AND_ASSIGN (scoped_fd);
59 ATTRIBUTE_UNUSED_RESULT int release () noexcept
61 int fd = m_fd;
62 m_fd = -1;
63 return fd;
66 /* Like release, but return a gdb_file_up that owns the file
67 descriptor. On success, this scoped_fd will be released. On
68 failure, return NULL and leave this scoped_fd in possession of
69 the fd. */
70 gdb_file_up to_file (const char *mode) noexcept
72 gdb_file_up result (fdopen (m_fd, mode));
73 if (result != nullptr)
74 m_fd = -1;
75 return result;
78 int get () const noexcept
80 return m_fd;
83 private:
84 int m_fd;
87 #endif /* COMMON_SCOPED_FD_H */