testsuite: skip confirmation in 'gdb_reinitialize_dir'
[binutils-gdb.git] / gdbsupport / scoped_fd.h
blobaa214b2c1c1ab6f07d68614d5ea1f2e807b8ccf5
1 /* scoped_fd, automatically close a file descriptor
3 Copyright (C) 2018-2024 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 "gdb_file.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 */