Do not reopen temporary files
[deliverable/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 <unistd.h>
24 #include "filestuff.h"
25
26 /* A smart-pointer-like class to automatically close a file descriptor. */
27
28 class scoped_fd
29 {
30 public:
31 explicit scoped_fd (int fd = -1) noexcept : m_fd (fd) {}
32 ~scoped_fd ()
33 {
34 if (m_fd >= 0)
35 close (m_fd);
36 }
37
38 DISABLE_COPY_AND_ASSIGN (scoped_fd);
39
40 int release () noexcept
41 {
42 int fd = m_fd;
43 m_fd = -1;
44 return fd;
45 }
46
47 /* Like release, but return a gdb_file_up that owns the file
48 descriptor. On success, this scoped_fd will be released. On
49 failure, return NULL and leave this scoped_fd in possession of
50 the fd. */
51 gdb_file_up to_file (const char *mode) noexcept
52 {
53 gdb_file_up result (fdopen (m_fd, mode));
54 if (result != nullptr)
55 m_fd = -1;
56 return result;
57 }
58
59 int get () const noexcept
60 {
61 return m_fd;
62 }
63
64 private:
65 int m_fd;
66 };
67
68 #endif /* SCOPED_FD_H */
This page took 0.038072 seconds and 5 git commands to generate.