CernVM-FS  2.13.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
file_guard.h
Go to the documentation of this file.
1 
5 #ifndef CVMFS_UTIL_FILE_GUARD_H_
6 #define CVMFS_UTIL_FILE_GUARD_H_
7 
8 #include <unistd.h>
9 
10 #include <cstdio>
11 #include <string>
12 
13 #include "util/single_copy.h"
14 
15 #ifdef CVMFS_NAMESPACE_GUARD
16 namespace CVMFS_NAMESPACE_GUARD {
17 #endif
18 
19 
24  public:
25  enum InitialState {
27  kDisabled
28  };
29 
30  inline UnlinkGuard() : enabled_(false) { }
31  inline explicit UnlinkGuard(const std::string &path,
32  const InitialState state = kEnabled)
33  : path_(path), enabled_(state == kEnabled) { }
34  inline ~UnlinkGuard() {
35  if (IsEnabled())
36  unlink(path_.c_str());
37  }
38 
39  inline void Set(const std::string &path) {
40  path_ = path;
41  Enable();
42  }
43 
44  inline bool IsEnabled() const { return enabled_; }
45  inline void Enable() { enabled_ = true; }
46  inline void Disable() { enabled_ = false; }
47 
48  const std::string &path() const { return path_; }
49 
50  private:
51  std::string path_;
52  bool enabled_;
53 };
54 
55 
60  public:
61  inline FdGuard() : fd_(-1) { }
62  explicit inline FdGuard(const int fd) : fd_(fd) { }
63  inline ~FdGuard() {
64  if (fd_ >= 0)
65  close(fd_);
66  }
67  int fd() const { return fd_; }
68 
69  private:
70  int fd_;
71 };
72 
73 
78  public:
79  inline FileGuard() : file_(NULL) { }
80  explicit inline FileGuard(FILE *file) : file_(file) { }
81  inline ~FileGuard() {
82  if (file_ != NULL)
83  fclose(file_);
84  }
85  const FILE *file() const { return file_; }
86 
87  private:
88  FILE *file_;
89 };
90 
91 
92 #ifdef CVMFS_NAMESPACE_GUARD
93 } // namespace CVMFS_NAMESPACE_GUARD
94 #endif
95 
96 #endif // CVMFS_UTIL_FILE_GUARD_H_
FILE * file_
Definition: file_guard.h:88
FdGuard()
Definition: file_guard.h:61
FileGuard(FILE *file)
Definition: file_guard.h:80
const FILE * file() const
Definition: file_guard.h:85
FdGuard(const int fd)
Definition: file_guard.h:62
~FileGuard()
Definition: file_guard.h:81
int fd_
Definition: file_guard.h:70
int fd() const
Definition: file_guard.h:67
~FdGuard()
Definition: file_guard.h:63