sbase

suckless unix tools
git clone git://git.suckless.org/sbase
Log | Files | Refs | README | LICENSE

mktemp.c (1641B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <libgen.h>
      3 #include <stdio.h>
      4 #include <stdlib.h>
      5 #include <string.h>
      6 #include <unistd.h>
      7 
      8 #include "util.h"
      9 
     10 static void
     11 usage(void)
     12 {
     13 	eprintf("usage: %s [-dqtu] [-p directory] [template]\n", argv0);
     14 }
     15 
     16 int
     17 main(int argc, char *argv[])
     18 {
     19 	int dflag = 0, pflag = 0, qflag = 0, tflag = 0, uflag = 0, fd;
     20 	char *template = "tmp.XXXXXXXXXX", *tmpdir = "", *pdir,
     21 	     *p, path[PATH_MAX], tmp[PATH_MAX];
     22 	size_t len;
     23 
     24 	ARGBEGIN {
     25 	case 'd':
     26 		dflag = 1;
     27 		break;
     28 	case 'p':
     29 		pflag = 1;
     30 		pdir = EARGF(usage());
     31 		break;
     32 	case 'q':
     33 		qflag = 1;
     34 		break;
     35 	case 't':
     36 		tflag = 1;
     37 		break;
     38 	case 'u':
     39 		uflag = 1;
     40 		break;
     41 	default:
     42 		usage();
     43 	} ARGEND
     44 
     45 	if (argc > 1)
     46 		usage();
     47 	else if (argc == 1)
     48 		template = argv[0];
     49 
     50 	if (!argc || pflag || tflag) {
     51 		if ((p = getenv("TMPDIR")))
     52 			tmpdir = p;
     53 		else if (pflag)
     54 			tmpdir = pdir;
     55 		else
     56 			tmpdir = "/tmp";
     57 	}
     58 
     59 	len = estrlcpy(path, tmpdir, sizeof(path));
     60 	if (path[0] && path[len - 1] != '/')
     61 		estrlcat(path, "/", sizeof(path));
     62 
     63 	estrlcpy(tmp, template, sizeof(tmp));
     64 	p = dirname(tmp);
     65 	if (!(p[0] == '.' && p[1] == '\0')) {
     66 		if (tflag && !pflag)
     67 			eprintf("template must not contain directory separators in -t mode\n");
     68 	}
     69 	estrlcat(path, template, sizeof(path));
     70 
     71 	if (dflag) {
     72 		if (!mkdtemp(path)) {
     73 			if (!qflag)
     74 				eprintf("mkdtemp %s:", path);
     75 			return 1;
     76 		}
     77 	} else {
     78 		if ((fd = mkstemp(path)) < 0) {
     79 			if (!qflag)
     80 				eprintf("mkstemp %s:", path);
     81 			return 1;
     82 		}
     83 		if (close(fd))
     84 			eprintf("close %s:", path);
     85 	}
     86 	if (uflag)
     87 		unlink(path);
     88 	puts(path);
     89 
     90 	efshut(stdout, "<stdout>");
     91 	return 0;
     92 }