Reputation: 483
I need to create new file in specific directory with a different name than all files in that directory. It doesn't have to be strictly "c++ code". It could be even bash or perl script that I'll call with execve, but I need to have access to its name from c ++ code.
How can I achieve this?
Upvotes: 3
Views: 1634
Reputation: 1
Since you've tagged the question gnu
and linux
, you can use the mkstemp()
fucntion:
DESCRIPTION
The
mkstemp()
function generates a unique temporary filename fromtemplate
, creates and opens the file, and returns an open file descriptor for the file.The last six characters of template must be
"XXXXXX"
and these are replaced with a string that makes the filename unique. Since it will be modified, template must not be a string constant, but should be declared as a character array.
For example:
char newFileName[] = "/path/to/new/file/someName.XXXXXX";
int newFileDescriptor = mkstemp( newFileName );
There are several other variations of the mkstemp()
function on the man page that might fit your actual needs better.
Depending on how secure your file creation process has to be, creating a hopefully-unique name for the new file and then making sure that the file you open is actually the new file you meant to create and not some other file swapped in by malicious code is not easy to do securely - there have been quite a few exploits that use the inherent race condition between code generating a name and then trying to create the new file to break into a system or otherwise compromise it.
And be aware that such constructs as UUIDs are not really guaranteed to be unique. If they're just random numbers, they can obviously not be guaranteed to be unique (although the odds of a collision may be vanishingly small). If they're not truly random numbers, they have a pattern that can be predicted and exploited by malicious code.
If security is a requirement, you'd do best to use the operating system's facilities for creating a new, unique file and giving your code an open file descriptor or handle to that new file.
Upvotes: 2
Reputation: 140
You can use UUID to create the name. Take a look at this
A question , but for windows, might help as well.
Upvotes: 1
Reputation: 1251
You can use C++
by generating an UUID on rather 32 or 64 bits, depending on what number of files you may generate.
Many libraries exist, like UUID Library
with boost if you can embedded an external library, or there are C Linux-based functions
Upvotes: 4