创建一个唯一的临时目录

use*_*186 4 c++ c++17

我正在尝试在系统临时文件夹中创建一个唯一的临时目录,并且已经阅读了tmpnam()的安全性和文件创建问题.

我写了下面的代码,并想知道它是否会满足这些问题,我是否正确使用了tmpnam()函数并抛出了filesystem_error?我是否应该为其他事情添加检查(例如temp_directory_path,它也会引发异常)?

    // Unique temporary directory path in the system temporary directory path.
std::filesystem::path tmp_dir_path {std::filesystem::temp_directory_path() /= std::tmpnam(nullptr)};

// Attempt to create the directory.
if (std::filesystem::create_directories(tmp_dir_path)) {

    // Directory successfully created.
    return tmp_dir_path;

} else {

    // Directory could not be created.
    throw std::filesystem_error("directory could not be created.");

}
Run Code Online (Sandbox Code Playgroud)

Dan*_*man 5

来自cppreference.com:

尽管std :: tmpnam生成的名称很难猜测,但是当std :: tmpnam返回时以及该程序尝试使用返回的名称创建的时候,有可能是另一个进程创建了具有该名称的文件.文件.

问题不在于你如何使用它,而在于你这样做的事实.

例如,在您的代码示例中,如果恶意用户成功地在第一行和第二行之间猜测并创建了目录,它可能会拒绝您的应用程序的服务(DOS),这可能是关键的,或者不是.

相反,有一种方法可以在不符合POSIX标准的系统上进行比赛:

  • 有关文件,请参阅mkstemp(3)以获取更多信息
  • 对于dirs,请参阅mkdtemp(3)以获取更多信息.