Version: SMASH-3.1
file.h
Go to the documentation of this file.
1 /*
2  *
3  * Copyright (c) 2014,2017-2018,2020,2022
4  * SMASH Team
5  *
6  * GNU General Public License (GPLv3 or later)
7  *
8  */
9 
10 #ifndef SRC_INCLUDE_SMASH_FILE_H_
11 #define SRC_INCLUDE_SMASH_FILE_H_
12 
13 #include <cerrno>
14 #include <cstdio>
15 #include <cstring>
16 #include <filesystem>
17 #include <memory>
18 #include <stdexcept>
19 #include <string>
20 
21 #include "forwarddeclarations.h"
22 
23 namespace smash {
24 
34 struct FileDeleter {
36  constexpr FileDeleter() = default;
37 
43  void operator()(std::FILE* f) const {
44  if (f == nullptr) {
45  return;
46  }
47  if (0 != std::fclose(f)) {
48  throw std::runtime_error(std::strerror(errno));
49  }
50  }
51 };
52 
61 using FilePtr = std::unique_ptr<std::FILE, FileDeleter>;
62 
73  public:
82  RenamingFilePtr(const std::filesystem::path& filename,
83  const std::string& mode);
85  FILE* get();
88 
89  private:
91  FILE* file_;
93  std::filesystem::path filename_;
95  std::filesystem::path filename_unfinished_;
102  int uncaught_exceptions_{std::uncaught_exceptions()};
103 };
104 
115 FilePtr fopen(const std::filesystem::path& filename, const std::string& mode);
116 
117 } // namespace smash
118 
119 #endif // SRC_INCLUDE_SMASH_FILE_H_
A RAII type to replace std::FILE *.
Definition: file.h:72
~RenamingFilePtr()
Close the file and rename it.
Definition: file.cc:29
std::filesystem::path filename_unfinished_
Path of the unfinished file.
Definition: file.h:95
std::filesystem::path filename_
Path of the finished file.
Definition: file.h:93
FILE * get()
Get the underlying FILE* pointer.
Definition: file.cc:27
RenamingFilePtr(const std::filesystem::path &filename, const std::string &mode)
Construct a RenamingFilePtr.
Definition: file.cc:19
int uncaught_exceptions_
Number of uncaught exceptions at the time when the object is created.
Definition: file.h:102
FILE * file_
Internal file pointer.
Definition: file.h:91
Definition: action.h:24
std::unique_ptr< std::FILE, FileDeleter > FilePtr
A RAII type to replace std::FILE *.
Definition: file.h:61
FilePtr fopen(const std::filesystem::path &filename, const std::string &mode)
Open a file with given mode.
Definition: file.cc:14
FileDeleter is the deleter class for std::unique_ptr of std::FILE.
Definition: file.h:34
constexpr FileDeleter()=default
The class has no members, so this is a noop.
void operator()(std::FILE *f) const
Frees the std::FILE resource if it is non-zero.
Definition: file.h:43