c – 创建一个唯一的临时目录
发布时间:2020-12-16 09:22:05 所属栏目:百科 来源:网络整理
导读:我正在尝试在系统临时文件夹中创建一个唯一的临时目录,并且已经阅读了tmpnam()的安全性和文件创建问题. 我写了下面的代码,并想知道它是否会满足这些问题,我使用tmpnam()函数是否正确并抛出filesystem_error?我应该为其他事情添加检查(例如temp_directory_pa
我正在尝试在系统临时文件夹中创建一个唯一的临时目录,并且已经阅读了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."); } 解决方法
你的代码很好.因为您尝试创建目录,操作系统将在您的进程和另一个尝试创建相同文件的进程之间进行仲裁,因此,如果您获胜,您拥有该文件,如果您丢失,则会收到错误.
我最近写了一个类似的功能.是否抛出异常取决于您希望如何使用此函数.例如,您可以简单地返回打开或关闭的std :: fstream并使用std :: fstream :: is_open作为成功度量,或者在失败时返回空路径名. 查看std::filesystem::create_directories,如果你不提供std :: error_code参数,它将抛出自己的异常,因此你不需要抛出自己的异常: std::filesystem::path tmp_dir_path {std::filesystem::temp_directory_path() /= std::tmpnam(nullptr)}; // Attempt to create the directory. std::filesystem::create_directories(tmp_dir_path)); // If that failed an exception will have been thrown // so no need to check or throw your own // Directory successfully created. return tmp_dir_path; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |