orl*_*rlp 41 c++ temporary-files
我正在寻找一种跨平台的方式来获取指定的临时文件.例如,在linux中,它将位于/tmp
dir中,而在Windows中则位于一些名为Internet Explorer的临时目录中.
是否存在跨平台(Boost?)解决方案?
编辑:
我需要这个文件存在,直到程序终止.tmpfile()
不能保证.引用ccpreference:
当流关闭(fclose) 或程序正常终止时,将自动删除创建的临时文件.
小智 80
在提高文件系统库,该库的版本3,可用于创建一个临时文件名.它还提供了一个清晰的解决方案.实际上,以下C++代码应该是平台无关的:
// Boost.Filesystem VERSION 3 required
#include <string>
#include <boost/filesystem.hpp>
boost::filesystem::path temp = boost::filesystem::unique_path();
const std::string tempstr = temp.native(); // optional
Run Code Online (Sandbox Code Playgroud)
文件系统路径对象temp
可用于打开文件或创建子目录,而字符串对象tempstr
提供与字符串相同的信息.有关详细信息,请访问http://www.boost.org.
标准C库包含一个名为的函数tmpfile
,它可能满足您的需求:http://www.cplusplus.com/reference/clibrary/cstdio/tmpfile/
您也可以在C++程序中使用它.
编辑:
如果你只需要文件名,你可以使用tmpnam
,它不会在调用fclose时删除文件.它返回完整的文件路径,包括临时目录.
C方式:
const char *name = tmpnam(NULL); // Get temp name
FILE *fp = fopen(name, "w"); // Create the file
// ...
fclose(fp);
remove(name);
Run Code Online (Sandbox Code Playgroud)