mktemp.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. /* Coreutils 6.12 man page says:
  12. * mktemp [OPTION]... [TEMPLATE]
  13. * Create a temporary file or directory, safely, and print its name. If
  14. * TEMPLATE is not specified, use tmp.XXXXXXXXXX.
  15. * -d, --directory
  16. * create a directory, not a file
  17. * -q, --quiet
  18. * suppress diagnostics about file/dir-creation failure
  19. * -u, --dry-run
  20. * do not create anything; merely print a name (unsafe)
  21. * --tmpdir[=DIR]
  22. * interpret TEMPLATE relative to DIR. If DIR is not specified,
  23. * use $TMPDIR if set, else /tmp. With this option, TEMPLATE must
  24. * not be an absolute name. Unlike with -t, TEMPLATE may contain
  25. * slashes, but even here, mktemp still creates only the final com-
  26. * ponent.
  27. * -p DIR use DIR as a prefix; implies -t [deprecated]
  28. * -t interpret TEMPLATE as a single file name component, relative to
  29. * a directory: $TMPDIR, if set; else the directory specified via
  30. * -p; else /tmp [deprecated]
  31. */
  32. #include "libbb.h"
  33. int mktemp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  34. int mktemp_main(int argc ATTRIBUTE_UNUSED, char **argv)
  35. {
  36. const char *path;
  37. char *chp;
  38. unsigned opt;
  39. opt_complementary = "?1"; /* 1 argument max */
  40. opt = getopt32(argv, "dqtp:", &path);
  41. chp = argv[optind] ? argv[optind] : xstrdup("tmp.XXXXXX");
  42. if (opt & (4|8)) { /* -t and/or -p */
  43. const char *dir = getenv("TMPDIR");
  44. if (dir && *dir != '\0')
  45. path = dir;
  46. else if (!(opt & 8)) /* no -p */
  47. path = "/tmp/";
  48. /* else path comes from -p DIR */
  49. chp = concat_path_file(path, chp);
  50. }
  51. if (opt & 1) { /* -d */
  52. if (mkdtemp(chp) == NULL)
  53. return EXIT_FAILURE;
  54. } else {
  55. if (mkstemp(chp) < 0)
  56. return EXIT_FAILURE;
  57. }
  58. puts(chp);
  59. return EXIT_SUCCESS;
  60. }