由于tmpfile()
的工作原理,如果您需要文件的名称,您不能使用它。不过,我已经创建了一个模块来处理临时文件。它使用条件编译来决定寻找临时目录的方法。在Windows上,它使用%TMP%环境变量。在Posix上,它使用/ tmp /。
此代码是根据WTFPL授权的,因此您可以随心所欲地做任何事情。
module TemporaryFiles;
import std.conv,
std.random,
std.stdio;
version(Windows) {
import std.process;
}
private static Random rand;
/// Returns a file with the specified filename and permissions
public File getTempFile(string filename, string permissions) {
string path;
version(Windows) {
path = getenv("TMP") ~ '\\';
} else version(Posix) {
path = "/tmp/";
// path = "/var/tmp/"; // Uncomment to survive reboots
}
return File(path~filename, permissions);
}
/// Returns a file opened for writing, which the specified filename
public File getTempFile(string filename) {
return getTempFile(filename, "w");
}
/// Returns a file opened for writing, with a randomly generated filename
public File getTempFile() {
string filename = to!string(uniform(1L, 1000000000L, rand)) ~ ".tmp";
return getTempFile(filename, "w");
}
要使用它,只需使用所需的任何参数调用getTempFile()。默认为写入权限。
作为说明,“随机生成的文件名”并非真正随机的,因为种子是在编译时设置的。