如何在C++;? 我在C++中写了一个函数,它创建了一个临时目录。此类功能应尽可能具有可移植性,例如,它应在linux、mac和win32环境下工作。我如何做到这一点
如何在C++;? 我在C++中写了一个函数,它创建了一个临时目录。此类功能应尽可能具有可移植性,例如,它应在linux、mac和win32环境下工作。我如何做到这一点,c++,linux,winapi,temporary-directory,C++,Linux,Winapi,Temporary Directory,mkdtemp(字符*模板) 创建一个临时目录。检查mkdtemp函数。没有标准函数可以执行此操作,因此您需要为每个目标平台编译不同的实现 using namespace boost::filesystem; path ph = temp_directory_path() / unique_path(); create_directories(ph); 例如,在Windows上,您应该使用temp目录,该目录可以通过调用GetTempPath()获得。Boost的文件系统库提供独立于平台的
mkdtemp(字符*模板)
创建一个临时目录。检查
mkdtemp
函数。没有标准函数可以执行此操作,因此您需要为每个目标平台编译不同的实现
using namespace boost::filesystem;
path ph = temp_directory_path() / unique_path();
create_directories(ph);
例如,在Windows上,您应该使用temp目录,该目录可以通过调用GetTempPath()获得。Boost的文件系统库提供独立于平台的目录函数。它会稍微增加您的程序大小,但使用Boost通常比使用自己的程序更好(而且更容易)
版本3的Boost文件系统库提供了函数
unique_path()
,用于生成适合创建临时文件或目录的路径名
using namespace boost::filesystem;
path ph = temp_directory_path() / unique_path();
create_directories(ph);
C++17
std::filesystem::temp\u directory\u path
+随机数生成
这里有一个可能可靠的纯C++17解决方案:没有Boost或其他外部库,也没有可用的mkdtemp
我们只是在随机数上循环,直到我们能够创建一个以前在内部不存在的目录(/tmp
在Ubuntu 18.04中)
然后,在完成创建的目录之后,我们可以显式地删除它
<> P> >我不确定C++标准是否保证了这一点,但极有可能是<代码> STD::FielSoS::TungDirectRyyPythPosie<代码>调用<代码> MKDIr < /C> >,它试图创建目录,如果不能用<代码> Ethys<代码>失败,那么我认为不会有并行调用方的竞争条件。
main.cpp
#include <exception>
#include <fstream>
#include <iostream>
#include <random>
#include <sstream>
#include <filesystem>
std::filesystem::path create_temporary_directory(
unsigned long long max_tries = 1000) {
auto tmp_dir = std::filesystem::temp_directory_path();
unsigned long long i = 0;
std::random_device dev;
std::mt19937 prng(dev());
std::uniform_int_distribution<uint64_t> rand(0);
std::filesystem::path path;
while (true) {
std::stringstream ss;
ss << std::hex << rand(prng);
path = tmp_dir / ss.str();
// true if the directory was created.
if (std::filesystem::create_directory(path)) {
break;
}
if (i == max_tries) {
throw std::runtime_error("could not find non-existing directory");
}
i++;
}
return path;
}
int main() {
auto tmpdir = create_temporary_directory();
std::cout << "create_temporary_directory() = "
<< tmpdir
<< std::endl;
// Use our temporary directory: create a file
// in it and write to it.
std::ofstream ofs(tmpdir / "myfile");
ofs << "asdf\nqwer\n";
ofs.close();
// Remove the directory and its contents.
std::filesystem::remove_all(tmpdir);
}
样本输出:
_directory.out
temp_directory_path() = "/tmp"
create_temporary_directory() = "/tmp/106adc08ff89874c"
有关文件,请参阅:文件有点不同,因为Linux中的open
具有O_TMPFILE
,因此专用的临时文件API可以通过使用它来提高效率。但是,mkdir
没有类似的标志,因此此解决方案可能是最优的
在Ubuntu 18.04中测试。
标准C++没有目录操作功能。POSIX标准确实有定义。所有现代操作系统都有一个POSIX兼容层(包括windows)。因此,mktemp()函数族就是您要寻找的。但是要小心,创建临时目录然后将文件放入其中是一个安全漏洞。直接创建文件描述符更安全。getenv()传递“TMP”如何?据我所知,Windows上不存在这种情况:(在标准c/c++中没有独立于平台的方法,在Windows上使用GetTempPath和GetTempFileName use tmpnam(),它是可移植的。我不想为此引入对boost的依赖。我遵循了您的文档链接。它只描述了如何创建临时文件。要求的是如何创建临时目录。