]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/common/scoped_fd.h
common: add scoped_fd
[thirdparty/binutils-gdb.git] / gdb / common / scoped_fd.h
1 /* scoped_fd, automatically close a file descriptor
2
3 Copyright (C) 2018 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
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.
11
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.
16
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/>. */
19
20 #ifndef SCOPED_FD_H
21 #define SCOPED_FD_H
22
23 #include "config.h"
24
25 #ifdef HAVE_UNISTD_H
26
27 #include <unistd.h>
28
29 /* A smart-pointer-like class to automatically close a file descriptor. */
30
31 class scoped_fd
32 {
33 public:
34 explicit scoped_fd (int fd = -1) noexcept : m_fd (fd) {}
35 ~scoped_fd ()
36 {
37 if (m_fd >= 0)
38 close (m_fd);
39 }
40
41 DISABLE_COPY_AND_ASSIGN (scoped_fd);
42
43 int release () noexcept
44 {
45 int fd = m_fd;
46 m_fd = -1;
47 return fd;
48 }
49
50 int get () const noexcept
51 {
52 return m_fd;
53 }
54
55 private:
56 int m_fd;
57 };
58
59 #endif /* HAVE_UNISTD_H */
60 #endif /* SCOPED_FD_H */