临时文件的使用需要注意:文件不可同时被多个任务编辑
char *tmpnam(char *s) 创建与当前已存在的所有文件不同名的文件
问题:其他程序也能open and edit与tmpnam返回的文件名同名的文件
注:文件名is assumed to至少L_tmpnam(通常是20)characters long
该函数至多能被调用TMP_MAX(至少几千)次in a single program.
FILE *tmpfile(void); 可避免上述文件同名问题,因为它创建的同时打开文件
返回的流指针指向唯一的临时文件并且创建的同时打开文件,文件模式可读可写,and
will be 自动删除 when all references to the file are closed.
代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char tmpname[L_tmpnam];
char *filename;
FILE *tmpfp;
filename=tmpnam(tmpname);
printf("temporary file name is: %s\n",filename);
tmpfp=tmpfile();
if(tmpfp)
printf("opened a temporary file OK\n");
else
perror("tmpfile");
exit(0);
}
输出:
temporary file name is: /tmp/filesUA8uL
opened a temporary file OK
UNIX版本提供了与tmpnam功能相同,except that you can specify a
template for the临时文件名,which gives you a little more 控制 over
文件的location and name
#include<stdlib.h>
char *mktemp(char *template);
int mkstemp(char *template);
总结:you should总是使用the “create and open”函数,比如tmpfile和mkstemp,
rather than tmpnam and mktemp函数。