如何创建具有唯一名称的文件?

How to create a file with unique name?

我需要在特定目录中使用与该目录中所有文件不同的名称创建新文件。它不一定是严格的 "c++ code"。它甚至可以是 bash 或我将使用 execve 调用的 perl 脚本,但我需要从 C++ 代码访问它的名称。

我怎样才能做到这一点?

您可以使用 UUID 创建名称。看看 this

A question ,但对于 windows 也可能有帮助。

您可以通过生成 32 位或 64 位的 UUID 来使用 C++,具体取决于您可能生成的文件数量。
存在许多库,例如 UUID Library with boost if you can embedded an external library,或者有基于 C Linux 的函数

由于您已标记问题 gnulinux,您可以使用 the mkstemp() fucntion:

描述

The mkstemp() function generates a unique temporary filename from template, 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.

例如:

char newFileName[] = "/path/to/new/file/someName.XXXXXX";
int newFileDescriptor = mkstemp( newFileName );

手册页上的 mkstemp() 函数还有其他几种变体,可能更适合您的实际需要。

根据您的文件创建过程的安全性,为新文件创建一个希望唯一的名称,然后确保您打开的文件实际上是您要创建的新文件,而不是其他文件通过恶意代码进行交换并不容易安全地进行 - 已经有相当多的利用代码生成名称之间的固有竞争条件,然后尝试创建新文件以闯入系统或以其他方式破坏它。

请注意,像 UUID 这样的结构并不能真正保证是唯一的。如果它们只是随机数,显然不能保证它们是唯一的(尽管碰撞的几率可能微乎其微)。如果它们不是真正的随机数,则它们具有可以被恶意代码预测和利用的模式。

如果安全是一项要求,您最好使用操作系统的工具来创建一个新的、唯一的文件,并为您的代码提供一个打开的文件描述符或该新文件的句柄。