Version: SMASH-1.5
file.h
Go to the documentation of this file.
1 /*
2  *
3  * Copyright (c) 2014-2018
4  * SMASH Team
5  *
6  * GNU General Public License (GPLv3 or later)
7  *
8  */
9 
10 #ifndef SRC_INCLUDE_FILE_H_
11 #define SRC_INCLUDE_FILE_H_
12 
13 #include <cerrno>
14 #include <cstdio>
15 #include <cstring>
16 #include <memory>
17 #include <stdexcept>
18 #include <string>
19 
20 #include <boost/filesystem.hpp>
21 
22 #include "cxx14compat.h"
23 #include "forwarddeclarations.h"
24 
25 namespace smash {
26 
36 struct FileDeleter {
38  constexpr FileDeleter() = default;
39 
45  void operator()(std::FILE* f) const {
46  if (f == nullptr) {
47  return;
48  }
49  if (0 != std::fclose(f)) {
50  throw std::runtime_error(std::strerror(errno));
51  }
52  }
53 };
54 
63 using FilePtr = std::unique_ptr<std::FILE, FileDeleter>;
64 
74  public:
83  RenamingFilePtr(const bf::path& filename, const std::string& mode);
85  FILE* get();
88 
89  private:
91  FILE* file_;
93  bf::path filename_;
96 };
97 
108 FilePtr fopen(const bf::path& filename, const std::string& mode);
109 
110 } // namespace smash
111 
112 #endif // SRC_INCLUDE_FILE_H_
FilePtr fopen(const bf::path &filename, const std::string &mode)
Open a file with given mode.
Definition: file.cc:14
FILE * file_
Internal file pointer.
Definition: file.h:91
FileDeleter is the deleter class for std::unique_ptr of std::FILE.
Definition: file.h:36
bf::path filename_
Path of the finished file.
Definition: file.h:93
constexpr FileDeleter()=default
The class has no members, so this is a noop.
A RAII type to replace std::FILE *.
Definition: file.h:73
bf::path filename_unfinished_
Path of the unfinished file.
Definition: file.h:95
std::unique_ptr< std::FILE, FileDeleter > FilePtr
A RAII type to replace std::FILE *.
Definition: file.h:63
RenamingFilePtr(const bf::path &filename, const std::string &mode)
Construct a RenamingFilePtr.
Definition: file.cc:19
~RenamingFilePtr()
Close the file and rename it.
Definition: file.cc:29
void operator()(std::FILE *f) const
Frees the std::FILE resource if it is non-zero.
Definition: file.h:45
Definition: action.h:24