1 |
|
|
/** |
2 |
|
|
* This file is part of the CernVM File System. |
3 |
|
|
*/ |
4 |
|
|
|
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 |
|
|
|
20 |
|
|
/** |
21 |
|
|
* RAII object to call `unlink()` on a containing file when it gets out of scope |
22 |
|
|
*/ |
23 |
|
|
class UnlinkGuard : SingleCopy { |
24 |
|
|
public: |
25 |
|
|
enum InitialState { kEnabled, kDisabled }; |
26 |
|
|
|
27 |
|
39 |
inline UnlinkGuard() : enabled_(false) {} |
28 |
|
613 |
inline UnlinkGuard(const std::string &path, |
29 |
|
|
const InitialState state = kEnabled) |
30 |
|
|
: path_(path) |
31 |
|
613 |
, enabled_(state == kEnabled) {} |
32 |
✓✓ |
651 |
inline ~UnlinkGuard() { if (IsEnabled()) unlink(path_.c_str()); } |
33 |
|
|
|
34 |
|
39 |
inline void Set(const std::string &path) { path_ = path; Enable(); } |
35 |
|
|
|
36 |
|
1256 |
inline bool IsEnabled() const { return enabled_; } |
37 |
|
122 |
inline void Enable() { enabled_ = true; } |
38 |
|
49 |
inline void Disable() { enabled_ = false; } |
39 |
|
|
|
40 |
|
1710 |
const std::string& path() const { return path_; } |
41 |
|
|
|
42 |
|
|
private: |
43 |
|
|
std::string path_; |
44 |
|
|
bool enabled_; |
45 |
|
|
}; |
46 |
|
|
|
47 |
|
|
|
48 |
|
|
/** |
49 |
|
|
* RAII object to close a file descriptor when it gets out of scope |
50 |
|
|
*/ |
51 |
|
|
class FdGuard : SingleCopy { |
52 |
|
|
public: |
53 |
|
|
inline FdGuard() : fd_(-1) { } |
54 |
|
1267 |
explicit inline FdGuard(const int fd) : fd_(fd) { } |
55 |
✓✗ |
1267 |
inline ~FdGuard() { if (fd_ >= 0) close(fd_); } |
56 |
|
|
int fd() const { return fd_; } |
57 |
|
|
|
58 |
|
|
private: |
59 |
|
|
int fd_; |
60 |
|
|
}; |
61 |
|
|
|
62 |
|
|
|
63 |
|
|
/** |
64 |
|
|
* RAII object to close a FILE stream when it gets out of scope |
65 |
|
|
*/ |
66 |
|
|
class FileGuard : SingleCopy { |
67 |
|
|
public: |
68 |
|
|
inline FileGuard() : file_(NULL) { } |
69 |
|
607 |
explicit inline FileGuard(FILE *file) : file_(file) { } |
70 |
✓✗ |
607 |
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_ |