利用mkstemp创建程序退出后不会被删除的临时文件

来源:互联网 发布:批量转换pdf软件 编辑:程序博客网 时间:2024/06/06 08:49

int mkstemp (char *template)

ENOENT为文件不存在时errno的值。

一、源代码:



  1 #include "apue.h"
  2 #include <sys/errno.h>
  3
  4 void make_tempfile(char *);
  5 int main()
  6 {
  7         char valid_name[] = "/tmp/dirXXXXXX";
  8         char *unvalid_name = "/tmp/dirXXXXXX";
  9         printf("Trying to create the first temp file.\n");
 10         make_tempfile(valid_name);
 11         printf("Trying to create the second temp file.\n");
 12         make_tempfile(unvalid_name);
 13         exit(0);
 14 }
 15
 16 void make_tempfile (char *template)
 17 {
 18 //      FILE *fp;
 19         struct stat buf;
 20         int fd;
 21         if ((fd = mkstemp(template)) < 0)
 22                 err_sys("mkstemp error");
 23         printf("file name:%s.\n",template);
 24         close (fd);
 25         if (stat(template,&buf) < 0){
 26                 if(errno == ENOENT)
 27                         err_sys("file doesn't exist");
 28                 else
 29                         err_sys("stat error");
 30         }
 31         else{
 32                 printf("file exist\n");
 33                 unlink(template);
 34         }
 35 }


二、执行结果:

<bldc:/home/tingbinz/apue.3e/SBSCODE/5>R*_*G:./crt_ext_tmpf
Trying to create the first temp file.
file name:/tmp/dircPaWtk.
file exist
Trying to create the second temp file.
Segmentation Fault(coredump)


0 0
原创粉丝点击