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, ">1uqd(directory)p(tmpdir):", TOYFLAG_BIN))
8
9 config MKTEMP
10 bool "mktemp"
11 default y
12 help
13 usage: mktemp [-dqu] [-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 -u Don't create anything, just print what would be created
21
22 Each X in TEMPLATE is replaced with a random printable character. The
23 default TEMPLATE is tmp.XXXXXX, and the default DIR is $TMPDIR if set,
24 else "/tmp".
25 */
26
27 #define FOR_mktemp
28 #include "toys.h"
29
GLOBALS(char * tmpdir;)30 GLOBALS(
31 char *tmpdir;
32 )
33
34 void mktemp_main(void)
35 {
36 int d_flag = toys.optflags & FLAG_d;
37 char *template = *toys.optargs;
38
39 if (!template) template = "tmp.XXXXXX";
40
41 if (!TT.tmpdir) TT.tmpdir = getenv("TMPDIR");
42 if (!TT.tmpdir || !*TT.tmpdir) TT.tmpdir = "/tmp";
43
44 template = strchr(template, '/') ? xstrdup(template)
45 : xmprintf("%s/%s", TT.tmpdir, template);
46
47 if (d_flag ? !mkdtemp(template) : mkstemp(template) == -1) {
48 if (toys.optflags & FLAG_q) toys.exitval = 1;
49 else perror_exit("Failed to create %s %s/%s",
50 d_flag ? "directory" : "file", TT.tmpdir, template);
51 } else {
52 if (toys.optflags & FLAG_u) unlink(template);
53 xputs(template);
54 }
55
56 if (CFG_TOYBOX_FREE) free(template);
57 }
58