产生唯一的临时文件mkstemp()

INUX下建立临时的方法(函数)有很多, mktemp, tmpfile等等. 今天只推荐最安全最好用的一种: mkstemp.

mkstemp (建立唯一临时文件)
头文件: #include <stdlib.h>

声明:   int mkstemp(char *template)
返回值: 成功则返回0, 失败则返回-1
.
说明:  建立唯一临时文件名, template须以数组形式声明而非指针形式. 
        template格式为: template.XXXXXX. 最后6位必须为XXXXXX, 前缀随意.

//1.mkstemp函数在系统中以唯一的文件名创建一个文件并打开,而且只有当前用户才能访问这个临时文件,
//2.mkstemp函数只有一个参数,这个参数是个以“XXXXXX”结尾的非空字符串。mkstemp函数会用随机产生的字符串替换“XXXXXX”,保证 了文件名的唯一性
//3.由于mkstemp函数创建的临时文件不能自动删除,所以执行完 mkstemp函数后要调用unlink函数,unlink函数删除文件的目录入口

char temp_template[] = "/tmp/htp.XXXXXX";

tfd = mkstemp(temp_template);
if(!(tfp = fdopen(tfd,"w"))) {
fprintf(stderr,"Could not open temp file. ");
exit(1);
}

#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int fd;
char temp_file[]="tmp_XXXXXX";
/*Creat a temp file.*/
if((fd=mkstemp(temp_file))==-1)
{
printf("Creat temp file faile./n");
exit(1);
}
/*Unlink the temp file.*/
unlink(temp_file);
/*Then you can read or write the temp file.*/
//ADD YOUR CODE;
/*Close temp file, when exit this program, the temp file will be removed.*/
close(fd);
}
原文地址:https://www.cnblogs.com/zhouhbing/p/4201126.html