Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Portable generation of a new file name in a specified directory

Tags:

c++

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.

like image 609
andreas buykx Avatar asked Nov 05 '10 15:11

andreas buykx


3 Answers

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:

  • Whenever possible, use library-provided functions instead of writing your own. For example, in Windows use GetTempFileName, on Linux use mkstemp.
  • Use 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.

like image 172
Nate Avatar answered Nov 18 '22 12:11

Nate


You could generate a UUID to create unique names. See this link for a list of implementations in C++.

like image 23
Justin Ethier Avatar answered Nov 18 '22 13:11

Justin Ethier


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;
like image 45
Scott Chamberlain Avatar answered Nov 18 '22 11:11

Scott Chamberlain