1414namespace bnw = boost::nowide;
1515namespace bfs = boost::filesystem;
1616
17+ constexpr unsigned MAX_TRIES = 50 ;
18+
1719namespace { // / Creates and opens a temporary binary file with the given extension
1820// / file must be a closed file stream and open() will be called on it
1921// / Returns the filename used or an empty string on error
2022bfs::path createTempFile (bnw::ofstream& file, const std::string& ext /* = ".tmp"*/ )
2123{
22- static const unsigned MAX_TRIES = 50 ;
23-
2424 if (file.is_open ())
2525 throw std::runtime_error (" Passed in an open file handle to createTempFile" );
2626
2727 // Temp directory (e.g. /tmp)
2828 bfs::path tmpPath = bfs::temp_directory_path ();
29- unsigned tries = 0 ;
30- do
29+
30+ for ( unsigned tries = 0 ; tries < MAX_TRIES; ++tries)
3131 {
3232 // Create a (hopefully) unique filePath
3333 bfs::path filePath = tmpPath / bfs::unique_path ();
@@ -46,7 +46,7 @@ bfs::path createTempFile(bnw::ofstream& file, const std::string& ext /* = ".tmp"
4646 continue ;
4747 }
4848 return filePath;
49- } while (++tries < MAX_TRIES);
49+ }
5050 // Could not find a file :(
5151 return " " ;
5252}
@@ -76,3 +76,28 @@ TmpFile::~TmpFile()
7676 stream.close ();
7777 unlinkFile (filePath);
7878}
79+
80+ TmpFolder::TmpFolder (boost::filesystem::path parent)
81+ {
82+ if (parent.empty ())
83+ parent = bfs::temp_directory_path ();
84+ for (unsigned tries = 0 ; tries < MAX_TRIES; ++tries)
85+ {
86+ // Create a (hopefully) unique filePath
87+ filePath = parent / bfs::unique_path ();
88+ if (!bfs::exists (filePath))
89+ {
90+ boost::system::error_code ec;
91+ bfs::create_directories (filePath, ec);
92+ if (!ec)
93+ return ;
94+ }
95+ }
96+ throw std::runtime_error (" Can't create temporary folder" );
97+ }
98+
99+ TmpFolder::~TmpFolder ()
100+ {
101+ boost::system::error_code ec;
102+ bfs::remove_all (filePath, ec);
103+ }
0 commit comments