Skip to content

Commit 16c51cf

Browse files
committed
Add TmpFolder for a temporary/auto-removed folder
1 parent d16fc41 commit 16c51cf

2 files changed

Lines changed: 42 additions & 5 deletions

File tree

libs/common/include/s25util/tmpFile.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,15 @@ class TmpFile
2929

3030
const boost::filesystem::path filePath;
3131
};
32+
33+
/// RAII wrapper for a temporary folder, that is created on construction and deleted on destruction
34+
class TmpFolder
35+
{
36+
boost::filesystem::path filePath;
37+
38+
public:
39+
explicit TmpFolder(boost::filesystem::path parent);
40+
~TmpFolder();
41+
42+
operator boost::filesystem::path() const { return filePath; }
43+
};

libs/common/src/tmpFile.cpp

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,20 @@
1414
namespace bnw = boost::nowide;
1515
namespace bfs = boost::filesystem;
1616

17+
constexpr unsigned MAX_TRIES = 50;
18+
1719
namespace { /// 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
2022
bfs::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

Comments
 (0)