问题描述
我看过一些与我的问题有关的帖子,但没有一篇能完全解决这个问题.我需要在标准临时目录中创建一个文件,完成写入后,将其移动到其他位置.想法是,该文件在下载时被视为临时文件,在下载完成后被视为永久文件.
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.
我正在尝试通过调用 mkstemp 或tmpfile ,然后重命名写完之后.但是,我需要文件的完整路径来调用重命名,并且显然从文件描述符(由mkstemp返回)或FILE *(由tmpfile返回)获取文件名并非易事.可以做到,但并不优雅.
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.
是否存在将创建临时文件并提供名称的系统调用?我知道 mktemp 和相关的调用,但是不能保证它们是唯一的或不推荐使用.或者也许有更好的方法来完成创建,写入和移动临时文件的操作.
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.
推荐答案
它看起来像 mkstemp
实际上是要走的路.
It looks like mkstemp
is actually the way to go.
int fd;
char name[] = "/tmp/fileXXXXXX";
fd = mkstemp(name);
/* Check fd. */
此调用之后,您在fd
中具有有效的描述符,在name
中具有关联文件的名称.
After this call you have a valid descriptor in fd
and the name of the associated file in name
.
这篇关于如何获得一个临时文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!