CASM
AClustersApproachtoStatisticalMechanics
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules
SafeOfstream.hh
Go to the documentation of this file.
1 #ifndef CASM_SafeOfstream
2 #define CASM_SafeOfstream
3 
4 #include <string>
5 #include <vector>
6 #include "casm/external/boost.hh"
8 
9 namespace CASM {
10 
18  // // throws if "something.json.tmp" already exists
28  class SafeOfstream {
29 
30  public:
31 
33 
62  void open(fs::path name, std::string tmp_ext = "tmp") {
63  m_name = name;
64  m_tmp_name = m_name.string() + "." + tmp_ext;
65 
66  if(fs::exists(m_tmp_name)) {
67  throw std::runtime_error(
68  std::string("Error in 'SafeOfstream::open(fs::path name, std::string tmp_ext)'.\n") +
69  " File: " + m_tmp_name.string() + " already exists");
70  }
71 
72  m_sout.open(m_tmp_name);
73  }
74 
76  fs::ofstream &ofstream() {
77  return m_sout;
78  }
79 
81  void close() {
82  m_sout.close();
83  if(!m_sout.fail()) {
84  fs::remove(m_name);
85  fs::rename(m_tmp_name, m_name);
86  }
87  }
88 
89  private:
90 
93  fs::ofstream m_sout;
94 
95 
96  };
97 
98 
99 }
100 
101 #endif
void close()
Closes stream, and if not a failed write, removes "file" and renames "file.tmp" to "file"...
Definition: SafeOfstream.hh:81
Main CASM namespace.
Definition: complete.cpp:8
Write to a temporary file to ensure a good write, then rename.
Definition: SafeOfstream.hh:28
fs::ofstream & ofstream()
Access underlying stream.
Definition: SafeOfstream.hh:76
void open(fs::path name, std::string tmp_ext="tmp")
Opens "file.tmp" for writing, with intended final target "file".
Definition: SafeOfstream.hh:62
fs::ofstream m_sout
Definition: SafeOfstream.hh:93