mktemp.c (1446B)
1 /* See LICENSE file for copyright and license details. */ 2 #include <libgen.h> 3 #include <limits.h> 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <string.h> 7 #include <unistd.h> 8 9 #include "util.h" 10 11 static void 12 usage(void) 13 { 14 eprintf("usage: %s [-dq] [template]\n", argv0); 15 } 16 17 static int dflag = 0; 18 static int qflag = 0; 19 20 int 21 main(int argc, char *argv[]) 22 { 23 char *template = "tmp.XXXXXXXXXX"; 24 char *tmpdir = "/tmp", *p; 25 char path[PATH_MAX], tmp[PATH_MAX]; 26 int fd; 27 28 ARGBEGIN { 29 case 'd': 30 dflag = 1; 31 break; 32 case 'q': 33 qflag = 1; 34 break; 35 default: 36 usage(); 37 } ARGEND; 38 39 if (argc > 1) 40 usage(); 41 else if (argc == 1) 42 template = argv[0]; 43 44 if ((p = getenv("TMPDIR"))) 45 tmpdir = p; 46 47 if (strlcpy(tmp, template, sizeof(tmp)) >= sizeof(tmp)) 48 eprintf("path too long\n"); 49 p = dirname(tmp); 50 if (p[0] != '.') { 51 if (strlcpy(path, template, sizeof(path)) >= sizeof(path)) 52 eprintf("path too long\n"); 53 } else { 54 if (strlcpy(path, tmpdir, sizeof(path)) >= sizeof(path)) 55 eprintf("path too long\n"); 56 if (strlcat(path, "/", sizeof(path)) >= sizeof(path)) 57 eprintf("path too long\n"); 58 if (strlcat(path, template, sizeof(path)) >= sizeof(path)) 59 eprintf("path too long\n"); 60 } 61 62 if (dflag) { 63 if (!mkdtemp(path)) { 64 if (!qflag) 65 eprintf("mkdtemp %s:", path); 66 exit(1); 67 } 68 } else { 69 if ((fd = mkstemp(path)) < 0) { 70 if (!qflag) 71 eprintf("mkstemp %s:", path); 72 exit(1); 73 } 74 close(fd); 75 } 76 puts(path); 77 return 0; 78 }