c++ - 创建一个唯一的临时目录

标签 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.");

}

最佳答案

来自 cppreference.com :

Although the names generated by std::tmpnam are difficult to guess, it is possible that a file with that name is created by another process between the moment std::tmpnam returns and the moment this program attempts to use the returned name to create a file.

问题不在于您如何使用它,而在于您使用它的事实。

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

相反,有一种方法可以在不与 POSIX 兼容的系统上进行竞争:

  • 有关文件,请参阅 mkstemp(3)了解更多信息
  • 有关目录,请参阅 mkdtemp(3)了解更多信息。

关于c++ - 创建一个唯一的临时目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52912981/

相关文章:

c++ - std::experimental::source_location 如何实现?

c++ - 可见性生效时如何导出公共(public)内部/嵌套类?

c++ - 如何获得 std::set 的相对索引?

c++ - AtmelATAES132 Mac一代

c++ - 用于重新排序无符号整数的 Constexpr 变量模板

c++ - 使用 C++20 比较 std::variant 和 int <=> 不是常量表达式

c++ - 如何有效地将底层数据从 std::string 移动到另一种类型的变量?

c++ - 从临时返回按值 string_view 时,有没有办法获得编译器警告?

c++ - 是否应该将运算符声明为非成员非模板 friend

c++ - 将 Matlab 与 C++ 链接时出错