2012-02-21 45 views
0

我需要生成一个临时文件,填充一些数据并将其提供给外部程序。基于d的描述可here我使用​​方法:如何获取由D2中的File.tmpfile创建的临时文件的名称?

auto f = File.tmpfile(); 
writeln(f.name()); 

不提供一种方式来获得所生成的文件名。据记载,name可能是空的。在Python中,我会这样做:

(o_fd, o_filename) = tempfile.mkstemp('.my.own.suffix') 

在D2中有没有一种简单,安全和跨平台的方法?

回答

0

由于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()。默认为写入权限。

作为说明,“随机生成的文件名”并非真正随机的,因为种子是在编译时设置的。

相关问题