简体   繁体   English

如何获取临时文件名?

[英]How to get a temporary file name?

I've seen some posts relating to my question, but none that address it completely. 我看过一些与我的问题相关的帖子,但没有一个完全解决它。 I need to create a file in the standard temporary directory and after I'm done writing to it, move it to a different location. 我需要在标准临时目录中创建一个文件,在我写完文件后,将其移动到其他位置。 The idea is that the file is considered temporary while being downloaded and permanent after downloading completes. 这个想法是文件在下载时被认为是临时的,在下载完成后是永久性的。

I'm attempting this by calling either mkstemp or tmpfile , then rename after I'm done writing to it. 我是通过调用mkstemptmpfile来尝试这个,然后在我写完之后重命名 However, I need the full path of the file to call rename, and apparently getting the file name from a file descriptor (returned by mkstemp) or FILE * (returned by tmpfile) is no trivial process. 但是,我需要文件的完整路径来调用重命名,显然从文件描述符(由mkstemp返回)或FILE *(由tmpfile返回)获取文件名不是一个简单的过程。 It can be done, but it's not elegant. 它可以做到,但它并不优雅。

Is there a system call that will create a temporary file and provide me with the name? 是否有系统调用将创建临时文件并为我提供名称? I know about mktemp and related calls, but they either aren't guaranteed to be unique or are deprecated. 我知道mktemp和相关的调用,但它们要么不保证是唯一的,要么被弃用。 Or perhaps there is a better way to accomplish creating, writing to, and moving temporary files. 或者也许有更好的方法来完成创建,写入和移动临时文件。

It looks like mkstemp is actually the way to go. 看起来mkstemp实际上是要走的路。

int fd;
char name[] = "/tmp/fileXXXXXX";
fd = mkstemp(name);
/* Check fd. */

After this call you have a valid descriptor in fd and the name of the associated file in name . 在此调用之后,您在fd有一个有效的描述符,并且名称中包含相关文件的name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM