如何在Windows XP / Vista上创建临时文件的路径

时间:2020-03-06 14:20:27  来源:igfitidea点击:

最好的方法是什么?
tmpnam()返回驱动器根目录中文件的路径,该路径需要Windows Vista上的管理员权限,因此这不是一个选择。

解决方案

我们是否尝试过将环境变量TEMP和TMP设置为所有人都可写的目录?
要在XP(不熟悉Vista)中更改环境变量,请转到系统属性,[高级]选项卡,[环境变量]按钮。

GetTempPath和GetTempFileName应该工作。

Windows上的环境变量%TEMP%指向用户的temp目录。

在托管C ++中,我们可以调用Path :: GetTempFileName(),这将在用户的temp目录中提供一个临时文件(可以使用Path :: GetTempPath()找到)。 GetTempFileName()基本上只是使用GUID作为文件名,为我们提供%TEMP%路径中文件的路径。然后,我们可以使用该路径创建文件并对其进行所需的操作。我们可以使用可以访问当前流程环境变量的任何语言执行类似的逻辑。

希望能有所帮助,

马丁

也许我们可以在kernel32.dll中使用Win32方法GetTempPath()。通过System.IO.Path.GetTempFileName()将其包装在.NET中。

在XP上,这将返回C:\ Documents and Settings \ username \ Local Settings \ Temp \中的路径,因此我们不需要管理员权限。

如果我们关心互操作性,则tmpnam的手册页建议:

tmpnam手册页

BUGS
       Never use this function. Use mkstemp(3) instead.

mkstemp手册页

SYNOPSIS
       #include <stdlib.h>

       int mkstemp(char *template);

DESCRIPTION
       The mkstemp() function generates a unique temporary file name from template.  The last six characters of template must be
       XXXXXX and these are replaced with a string that makes the filename unique. The file is then created with mode read/write

但是所有这些都表明我们已经准备了以TMP环境变量的内容为前缀的模板。