如何获取临时文件名?

时间:2022-04-27 03:39:15

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. 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. It can be done, but it's not elegant.

我是通过调用mkstemp或tmpfile来尝试这个,然后在我写完之后重命名。但是,我需要文件的完整路径来调用重命名,显然从文件描述符(由mkstemp返回)或FILE *(由tmpfile返回)获取文件名不是一个简单的过程。它可以做到,但它并不优雅。

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. Or perhaps there is a better way to accomplish creating, writing to, and moving temporary files.

是否有系统调用会创建一个临时文件并为我提供名称?我知道mktemp和相关的调用,但它们要么不保证是唯一的,要么被弃用。或者可能有更好的方法来完成创建,写入和移动临时文件。

1 个解决方案

#1


13  

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中有一个有效的描述符,并且名称中包含相关文件的名称。

#1


13  

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中有一个有效的描述符,并且名称中包含相关文件的名称。