Version: SMASH-3.1
file.cc
Go to the documentation of this file.
1 /*
2  *
3  * Copyright (c) 2018,2022
4  * SMASH Team
5  *
6  * GNU General Public License (GPLv3 or later)
7  *
8  */
9 
10 #include "smash/file.h"
11 
12 namespace smash {
13 
14 FilePtr fopen(const std::filesystem::path& filename, const std::string& mode) {
15  FilePtr f{std::fopen(filename.c_str(), mode.c_str())};
16  return f;
17 }
18 
19 RenamingFilePtr::RenamingFilePtr(const std::filesystem::path& filename,
20  const std::string& mode) {
21  filename_ = filename;
22  filename_unfinished_ = filename;
23  filename_unfinished_ += ".unfinished";
24  file_ = std::fopen(filename_unfinished_.c_str(), mode.c_str());
25 }
26 
27 FILE* RenamingFilePtr::get() { return file_; }
28 
30  std::fclose(file_);
31  // we rename the output file only if we are not unwinding the stack
32  // because of an exception
33  if (std::uncaught_exceptions() == uncaught_exceptions_) {
34  std::filesystem::rename(filename_unfinished_, filename_);
35  }
36 }
37 
38 } // namespace smash
~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