CASM  1.1.0
A Clusters Approach to Statistical Mechanics
SafeOfstream.hh
Go to the documentation of this file.
1 #ifndef CASM_SafeOfstream
2 #define CASM_SafeOfstream
3 
4 #include <boost/filesystem.hpp>
5 #include <boost/filesystem/fstream.hpp>
6 #include <string>
7 #include <vector>
8 
9 namespace CASM {
10 
11 namespace fs = boost::filesystem;
12 
21 // // throws if "something.json.tmp" already exists
31 class SafeOfstream {
32  public:
34 
65  void open(fs::path name, std::string tmp_ext = "tmp") {
66  m_name = name;
67  m_tmp_name = m_name.string() + "." + tmp_ext;
68 
69  if (fs::exists(m_tmp_name)) {
70  throw std::runtime_error(
71  std::string("Error in 'SafeOfstream::open(fs::path name, std::string "
72  "tmp_ext)'.\n") +
73  " File: " + m_tmp_name.string() + " already exists");
74  }
75 
76  m_sout.open(m_tmp_name);
77  }
78 
80  fs::ofstream &ofstream() { return m_sout; }
81 
84  void close() {
85  m_sout.close();
86  if (!m_sout.fail()) {
87  fs::remove(m_name);
88  fs::rename(m_tmp_name, m_name);
89  }
90  }
91 
92  private:
93  fs::path m_name;
94  fs::path m_tmp_name;
95  fs::ofstream m_sout;
96 };
97 
98 } // namespace CASM
99 
100 #endif
Write to a temporary file to ensure a good write, then rename.
Definition: SafeOfstream.hh:31
void close()
Closes stream, and if not a failed write, removes "file" and renames "file.tmp" to "file".
Definition: SafeOfstream.hh:84
fs::ofstream m_sout
Definition: SafeOfstream.hh:95
void open(fs::path name, std::string tmp_ext="tmp")
Opens "file.tmp" for writing, with intended final target "file".
Definition: SafeOfstream.hh:65
fs::ofstream & ofstream()
Access underlying stream.
Definition: SafeOfstream.hh:80
Main CASM namespace.
Definition: APICommand.hh:8
GenericDatumFormatter< std::string, DataObject > name()