CernVM-FS  2.9.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 { kEnabled, kDisabled };
26 
27  inline UnlinkGuard() : enabled_(false) {}
28  inline UnlinkGuard(const std::string &path,
29  const InitialState state = kEnabled)
30  : path_(path)
31  , enabled_(state == kEnabled) {}
32  inline ~UnlinkGuard() { if (IsEnabled()) unlink(path_.c_str()); }
33 
34  inline void Set(const std::string &path) { path_ = path; Enable(); }
35 
36  inline bool IsEnabled() const { return enabled_; }
37  inline void Enable() { enabled_ = true; }
38  inline void Disable() { enabled_ = false; }
39 
40  const std::string& path() const { return path_; }
41 
42  private:
43  std::string path_;
44  bool enabled_;
45 };
46 
47 
52  public:
53  inline FdGuard() : fd_(-1) { }
54  explicit inline FdGuard(const int fd) : fd_(fd) { }
55  inline ~FdGuard() { if (fd_ >= 0) close(fd_); }
56  int fd() const { return fd_; }
57 
58  private:
59  int fd_;
60 };
61 
62 
67  public:
68  inline FileGuard() : file_(NULL) { }
69  explicit inline FileGuard(FILE *file) : file_(file) { }
70  inline ~FileGuard() { if (file_ != NULL) fclose(file_); }
71  const FILE *file() const { return file_; }
72 
73  private:
74  FILE *file_;
75 };
76 
77 
78 #ifdef CVMFS_NAMESPACE_GUARD
79 } // namespace CVMFS_NAMESPACE_GUARD
80 #endif
81 
82 #endif // CVMFS_UTIL_FILE_GUARD_H_
FILE * file_
Definition: file_guard.h:74
FdGuard()
Definition: file_guard.h:53
FileGuard(FILE *file)
Definition: file_guard.h:69
const FILE * file() const
Definition: file_guard.h:71
FdGuard(const int fd)
Definition: file_guard.h:54
~FileGuard()
Definition: file_guard.h:70
int fd_
Definition: file_guard.h:59
int fd() const
Definition: file_guard.h:56
~FdGuard()
Definition: file_guard.h:55