[英]How do I open a temporary file AND get its filename?
I need to create a temporary file in my C program, write some data to it, and then invoke an external command (via exec or system) to do some processing on the file I just created. 我需要在C程序中创建一个临时文件,向其中写入一些数据,然后调用外部命令(通过exec或系统)对刚刚创建的文件进行一些处理。 I did not write the external command nor is it feasible to integrate it into my program so I don't think I can share an already open descriptor with it.
我没有编写外部命令,也没有将其集成到程序中的可行性,因此我认为我无法与它共享已经打开的描述符。 Therefore, I need to know the name of the temp file created.
因此,我需要知道所创建的临时文件的名称。
The tempname() function does this, but unfortunately it recommends that you don't use itself, due to a possible race condition between getting the name and opening the file, and neither of the functions it recommends (tmpfile and mkstemp) provide a way to find out the actual name of the file created. tempname()函数可以做到这一点,但不幸的是,由于在获取名称和打开文件之间可能存在竞争,因此建议您不要使用自身,并且建议的函数(tmpfile和mkstemp)都不提供方法找出创建的文件的实际名称。
It is not true that mkstemp
does not let you know the temporary file name, try to compile and execute this program to see yourself: 确实,
mkstemp
不会让您知道临时文件名,而是尝试编译并执行此程序以了解您自己:
#include <stdlib.h>
#include <stdio.h>
int main()
{
char fn[] = "/tmp/fileXXXXXX";
int fd = mkstemp(fn);
char cmd[200];
int n = snprintf(cmd, sizeof(cmd), "ls -l %s\n", fn);
printf("snprintf=>%d\n sizeof(fn)=%d\n", n, sizeof(fn)); // extra info, see comments
printf("%s\n", cmd);
return system(cmd);
}
mkstemp
will replace the file name template in the buffer you pass to it with actual file name, you can do whatever you want with this buffer later on. mkstemp
会将传递给它的缓冲区中的文件名模板替换为实际文件名,稍后您可以使用此缓冲区执行任何操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.