comparison toys/mktemp.c @ 586:0353ed084559

Convert mktemp to use xrealpath, and general clean up while there.
author Rob Landley <rob@landley.net>
date Fri, 01 Jun 2012 13:51:22 -0500
parents 953c22158c2e
children
comparison
equal deleted inserted replaced
585:1dcd7994abea 586:0353ed084559
15 usage: mktemp [OPTION] [TEMPLATE] 15 usage: mktemp [OPTION] [TEMPLATE]
16 16
17 Safely create a temporary file or directory and print its name. 17 Safely create a temporary file or directory and print its name.
18 TEMPLATE should end in 6 consecutive X's, the default 18 TEMPLATE should end in 6 consecutive X's, the default
19 template is tmp.XXXXXX and the default directory is /tmp/. 19 template is tmp.XXXXXX and the default directory is /tmp/.
20
20 -d, --directory Create a directory, instead of a file 21 -d, --directory Create a directory, instead of a file
21 -p DIR, --tmpdir=DIR Use DIR as a base path 22 -p DIR, --tmpdir=DIR Use DIR as a base path
22 23
23 */ 24 */
24 25
29 ) 30 )
30 #define TT this.mktemp 31 #define TT this.mktemp
31 32
32 void mktemp_main(void) 33 void mktemp_main(void)
33 { 34 {
34 int p_flag = (toys.optflags & 1); 35 int d_flag = toys.optflags & 2;
35 int d_flag = (toys.optflags & 2) >> 1; 36 char *tmp, *path;
36 char * result;
37 37
38 int size = snprintf(toybuf, sizeof(toybuf)-1, "%s/%s", 38 tmp = *toys.optargs;
39 (p_flag && TT.tmpdir)?TT.tmpdir:"/tmp/", 39 if (!tmp) tmp = "tmp.XXXXXX";
40 (toys.optargs[0])?toys.optargs[0]:"tmp.XXXXXX"); 40 if (!TT.tmpdir) TT.tmpdir = "/tmp/";
41 toybuf[size] = 0;
42 41
43 if (d_flag) { 42 tmp = xmsprintf("%s/%s", TT.tmpdir, tmp);
44 if (mkdtemp(toybuf) == NULL) 43
45 perror_exit("Failed to create temporary directory"); 44 if (d_flag ? mkdtemp(tmp) == NULL : mkstemp(tmp) == -1)
46 } else { 45 perror_exit("Failed to create temporary %s",
47 if (mkstemp(toybuf) == -1) 46 d_flag ? "directory" : "file");
48 perror_exit("Failed to create temporary file"); 47
48 xputs(path = xrealpath(tmp));
49
50 if (CFG_TOYBOX_FREE) {
51 free(path);
52 free(tmp);
49 } 53 }
50
51 result = realpath(toybuf, NULL);
52 xputs(result);
53
54 if (CFG_TOYBOX_FREE)
55 free(result);
56 } 54 }