Initial public busybox upstream commit
[busybox4maemo] / debianutils / mktemp.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini mktemp implementation for busybox
4  *
5  *
6  * Copyright (C) 2000 by Daniel Jacobowitz
7  * Written by Daniel Jacobowitz <dan@debian.org>
8  *
9  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
10  */
11
12 #include "libbb.h"
13
14 int mktemp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
15 int mktemp_main(int argc ATTRIBUTE_UNUSED, char **argv)
16 {
17         // -d      Make a directory instead of a file
18         // -q      Fail silently if an error occurs [bbox: ignored]
19         // -t      Generate a path rooted in temporary directory
20         // -p DIR  Use DIR as a temporary directory (implies -t)
21         const char *path;
22         char *chp;
23         unsigned flags;
24
25         opt_complementary = "=1"; /* exactly one arg */
26         flags = getopt32(argv, "dqtp:", &path);
27         chp = argv[optind];
28
29         if (flags & (4|8)) { /* -t and/or -p */
30                 const char *dir = getenv("TMPDIR");
31                 if (dir && *dir != '\0')
32                         path = dir;
33                 else if (!(flags & 8)) /* No -p */
34                         path = "/tmp/";
35                 /* else path comes from -p DIR */
36                 chp = concat_path_file(path, chp);
37         }
38
39         if (flags & 1) { /* -d */
40                 if (mkdtemp(chp) == NULL)
41                         return EXIT_FAILURE;
42         } else {
43                 if (mkstemp(chp) < 0)
44                         return EXIT_FAILURE;
45         }
46
47         puts(chp);
48
49         return EXIT_SUCCESS;
50 }