ROSE  0.9.10.27
Sawyer/FileSystem.h
1 // WARNING: Changes to this file must be contributed back to Sawyer or else they will
2 // be clobbered by the next update from Sawyer. The Sawyer repository is at
3 // https://github.com/matzke1/sawyer.
4 
5 
6 
7 
8 #ifndef Sawyer_FileSystem_H
9 #define Sawyer_FileSystem_H
10 
11 #include <Sawyer/Sawyer.h>
12 #include <boost/filesystem.hpp>
13 #include <boost/noncopyable.hpp>
14 #include <fstream>
15 
16 namespace Sawyer {
17 
19 namespace FileSystem {
20 
25 class SAWYER_EXPORT TemporaryFile: private boost::noncopyable {
26  boost::filesystem::path name_;
27  std::ofstream stream_;
28 
29 public:
32  name_ = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
33  stream_.open(name_.native().c_str());
34  }
35 
37  explicit TemporaryFile(const boost::filesystem::path &name) {
38  name_ = name;
39  stream_.open(name.native().c_str());
40  }
41 
46  stream_.close();
47  boost::filesystem::remove(name_);
48  }
49 
51  const boost::filesystem::path& name() const { return name_; }
52 
54  std::ofstream& stream() { return stream_; }
55 };
56 
61 class SAWYER_EXPORT TemporaryDirectory: private boost::noncopyable {
62  boost::filesystem::path name_;
63 
64 public:
69  : name_(boost::filesystem::temp_directory_path() / boost::filesystem::unique_path()) {
70  createOrThrow();
71  }
72 
77  explicit TemporaryDirectory(const boost::filesystem::path &name)
78  : name_(name) {
79  createOrThrow();
80  }
81 
87  boost::filesystem::remove_all(name_);
88  }
89 
91  const boost::filesystem::path& name() const { return name_; }
92 
93 private:
94  // Create directory or throw exception
95  void createOrThrow() {
96  boost::system::error_code ec;
97  if (!boost::filesystem::create_directory(name_, ec))
98  throw boost::filesystem::filesystem_error("cannot create directory", name_, ec);
99  }
100 };
101 
102 } // namespace
103 } // namespace
104 
105 #endif
const boost::filesystem::path & name() const
Path of temporary directory.
std::ofstream & stream()
Output stream for temporary file.
Creates a temporary file.
TemporaryDirectory()
Create a temporary subdirectory in the system's temp directory.
Name space for the entire library.
Definition: Access.h:13
TemporaryFile(const boost::filesystem::path &name)
Create a temporary file with the specified name.
~TemporaryFile()
Unlink the temporary file from the filesystem.
const boost::filesystem::path & name() const
Path of temporary file.
TemporaryDirectory(const boost::filesystem::path &name)
Create a temporary directory with the specified name.
TemporaryFile()
Create a temporary file in the system temp directory.
Create a temporary directory.
~TemporaryDirectory()
Recursively unlink the temporary directory.