Advanced Programming in UNIX Environment Episode 24
发布时间:2020-12-15 19:59:18 所属栏目:安全 来源:网络整理
导读:临时文件 提供了两个函数以帮助创建临时文件。 #include stdio.h char *tmpnam( char *ptr);FILE *tmpfile( void ); 嘴多调用次数是TMP_MAX。TMP_MAX定义在 stdio.h中。 #include "apue.h" int main( void ){ char name[L_tmpnam],line[MAXLINE]; FILE *fp;
临时文件 提供了两个函数以帮助创建临时文件。 #include <stdio.h>
char *tmpnam(char *ptr);
FILE *tmpfile(void);
嘴多调用次数是TMP_MAX。TMP_MAX定义在 <stdio.h>中。 #include "apue.h"
int main(void)
{
char name[L_tmpnam],line[MAXLINE];
FILE *fp;
printf("%sn",name);
tmpnam(name);
printf("%sn",name);
if((fp=tmpfile())==NULL)
err_sys("tmpfile error");
fputs("one line of outputn",fp);
rewind(fp);
if(gets(line,sizeof(line),fp)==NULL)
err_sys("fgets error");
fputs(line,stdout);
return 0;
}
tmpnam和tmpfile函数实例 Single UNIX Specification为处理临时定义了另外两个函数:mkdtemp和mkstemp,他们是XSI的扩展部分。 #include <stdlib.h>
char *mkdtemp(char *template);
int mkstemp(char *template);
使用tmpnam和tempnam至少有一个缺点:再返回唯一的路径名和用该名字创建文件之间存在一个时间窗口,在这个时间窗口中,另一个进程可以用相同名字创建文件。 #include "apue.h"
void make_temp(char *template);
int main(void)
{
char good_template[]="/tmp/dirXXXXXX";
char *bad_template[]="/tmp/dirXXXXXX";
printf("trying to create first temp file...n");
make_temp(good_template);
printf("trying to create second temp file...n");
make_temp(bad_template);
return 0;
}
void make_temp(char *template)
{
int fd;
struct stat sbuf;
if((fd=mkstemp(template))<0)
err_sys("can't create temp file");
printf("temp name=%sn",template);
close(fd);
if(stat(template,&sbuf)<0)
{
if(errno==ENOENT)
printf("file doesn't existn");
else
err_sys("stat failed");
}
else
{
printf("file existsn");
unlink(template);
}
}
mkstemp函数的应用 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |