mktemp.c revision 59d85e2bb065a3bdc27868acb7a65f89d872c7fa
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 7USE_MKTEMP(NEWTOY(mktemp, ">1q(directory)d(tmpdir)p:", TOYFLAG_BIN)) 8 9config MKTEMP 10 bool "mktemp" 11 default y 12 help 13 usage: mktemp [-dq] [-p DIR] [TEMPLATE] 14 15 Safely create new file and print its name. Default TEMPLATE is 16 /tmp/tmp.XXXXXX and each trailing X is replaced with random char. 17 18 -d, --directory Create directory instead of file 19 -p DIR, --tmpdir=DIR Put new file in DIR 20 -q Quiet 21*/ 22 23#define FOR_mktemp 24#include "toys.h" 25 26GLOBALS( 27 char * tmpdir; 28) 29 30void mktemp_main(void) 31{ 32 int d_flag = toys.optflags & FLAG_d; 33 char *tmp; 34 35 tmp = *toys.optargs; 36 37 if (!tmp) { 38 if (!TT.tmpdir) TT.tmpdir = "/tmp"; 39 tmp = "tmp.xxxxxx"; 40 } 41 if (TT.tmpdir) tmp = xmprintf("%s/%s", TT.tmpdir ? TT.tmpdir : "/tmp", 42 *toys.optargs ? *toys.optargs : "tmp.XXXXXX"); 43 44 if (d_flag ? mkdtemp(tmp) == NULL : mkstemp(tmp) == -1) 45 if (toys.optflags & FLAG_q) 46 perror_exit("Failed to create temporary %s", 47 d_flag ? "directory" : "file"); 48 49 xputs(tmp); 50 51 if (CFG_TOYBOX_FREE && TT.tmpdir) free(tmp); 52} 53