How can I portably (I am mostly interested in windows and linux) generate a new file name in a specified directory, with specified filename prefix and suffix?
std::string UniqueName(std::string const& dir, std::string const& prefix,
std::string const& suffix);
Any suggestions to implement this function, with as little as possible explicit dependencies on specific platforms.
Be aware that doing this wrong is a security hole. There are tricks to exploit temporary(ish) files, and these can give Administrator access to the whole system, not just your app. See this for some advice.
A couple of ways to do this:
GetTempFileName
, on Linux use mkstemp
.boost::filesystem::unique_path
, which lets you reliably generate unique filenames according to a template you provide.boost::filesystem
is scheduled to become a part of C++ TR2, which should be supported by almost all compilers in the future. Note that you must #define BOOST_FILESYSTEM_VERSION 3
(info), otherwise you’ll get an older version of boost::filesystem
that doesn’t support unique_path
.
You could generate a UUID to create unique names. See this link for a list of implementations in C++.
For a windows solution, Generate a guid and use it as the filename
Here is the code to generate the guid to get you started.
_TUCHAR *guidStr = 0x00;
GUID *pguid = 0x00;
pguid = new GUID;
CoCreateGuid(pguid);
// Convert the GUID to a string
UuidToString(pguid, &guidStr);
delete pguid;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With