1 /* mktemp.c - Create a temporary file or directory.
2 *
3 * Copyright 2012 Elie De Brauwer <eliedebrauwer@gmail.com>
4 *
5 * http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/mktemp.html
6
7 USE_MKTEMP(NEWTOY(mktemp, ">1qd(directory)p(tmpdir):", TOYFLAG_BIN))
8
9 config MKTEMP
10 bool "mktemp"
11 default y
12 help
13 usage: mktemp [-dq] [-p DIR] [TEMPLATE]
14
15 Safely create a new file "DIR/TEMPLATE" and print its name.
16
17 -d Create directory instead of file (--directory)
18 -p Put new file in DIR (--tmpdir)
19 -q Quiet, no error messages
20
21 Each X in TEMPLATE is replaced with a random printable character. The
22 default TEMPLATE is tmp.XXXXXX, and the default DIR is $TMPDIR if set,
23 else "/tmp".
24 */
25
26 #define FOR_mktemp
27 #include "toys.h"
28
GLOBALS(char * tmpdir;)29 GLOBALS(
30 char *tmpdir;
31 )
32
33 void mktemp_main(void)
34 {
35 int d_flag = toys.optflags & FLAG_d;
36 char *template = *toys.optargs;
37
38 if (!template) template = "tmp.XXXXXX";
39
40 if (!TT.tmpdir) TT.tmpdir = getenv("TMPDIR");
41 if (!TT.tmpdir || !*TT.tmpdir) TT.tmpdir = "/tmp";
42
43 template = strchr(template, '/') ? xstrdup(template)
44 : xmprintf("%s/%s", TT.tmpdir, template);
45
46 if (d_flag ? !mkdtemp(template) : mkstemp(template) == -1) {
47 if (toys.optflags & FLAG_q) toys.exitval = 1;
48 else perror_exit("Failed to create %s %s/%s",
49 d_flag ? "directory" : "file", TT.tmpdir, template);
50 } else xputs(template);
51
52 if (CFG_TOYBOX_FREE) free(template);
53 }
54