Mercurial > hg > toybox
comparison toys/mktemp.c @ 575:953c22158c2e
Addition of mktemp
author | Elie De Brauwer <eliedebrauwer@gmail.com> |
---|---|
date | Tue, 01 May 2012 11:45:45 +0200 |
parents | |
children | 0353ed084559 |
comparison
equal
deleted
inserted
replaced
574:d8effa95a5f0 | 575:953c22158c2e |
---|---|
1 /* vi: set sw=4 ts=4: | |
2 * | |
3 * mktemp.c - Create a temporary file or directory. | |
4 * | |
5 * Copyright 2012 Elie De Brauwer <eliedebrauwer@gmail.com> | |
6 * | |
7 * Not in SUSv4. | |
8 | |
9 USE_MKTEMP(NEWTOY(mktemp, ">1(directory)d(tmpdir)p:", TOYFLAG_BIN)) | |
10 | |
11 config MKTEMP | |
12 bool "mktemp" | |
13 default y | |
14 help | |
15 usage: mktemp [OPTION] [TEMPLATE] | |
16 | |
17 Safely create a temporary file or directory and print its name. | |
18 TEMPLATE should end in 6 consecutive X's, the default | |
19 template is tmp.XXXXXX and the default directory is /tmp/. | |
20 -d, --directory Create a directory, instead of a file | |
21 -p DIR, --tmpdir=DIR Use DIR as a base path | |
22 | |
23 */ | |
24 | |
25 #include "toys.h" | |
26 | |
27 DEFINE_GLOBALS( | |
28 char * tmpdir; | |
29 ) | |
30 #define TT this.mktemp | |
31 | |
32 void mktemp_main(void) | |
33 { | |
34 int p_flag = (toys.optflags & 1); | |
35 int d_flag = (toys.optflags & 2) >> 1; | |
36 char * result; | |
37 | |
38 int size = snprintf(toybuf, sizeof(toybuf)-1, "%s/%s", | |
39 (p_flag && TT.tmpdir)?TT.tmpdir:"/tmp/", | |
40 (toys.optargs[0])?toys.optargs[0]:"tmp.XXXXXX"); | |
41 toybuf[size] = 0; | |
42 | |
43 if (d_flag) { | |
44 if (mkdtemp(toybuf) == NULL) | |
45 perror_exit("Failed to create temporary directory"); | |
46 } else { | |
47 if (mkstemp(toybuf) == -1) | |
48 perror_exit("Failed to create temporary file"); | |
49 } | |
50 | |
51 result = realpath(toybuf, NULL); | |
52 xputs(result); | |
53 | |
54 if (CFG_TOYBOX_FREE) | |
55 free(result); | |
56 } |