mktemp.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 GPLv2 or later, see file LICENSE in this source tree.
  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 UNUSED_PARAM, char **argv)
  35. {
  36. const char *path;
  37. char *chp;
  38. unsigned opts;
  39. path = getenv("TMPDIR");
  40. if (!path || path[0] == '\0')
  41. path = "/tmp";
  42. /* -q and -t are ignored */
  43. opt_complementary = "?1"; /* 1 argument max */
  44. opts = getopt32(argv, "dqtp:", &path);
  45. chp = argv[optind] ? argv[optind] : xstrdup("tmp.XXXXXX");
  46. if (!strchr(chp, '/') || (opts & 8))
  47. chp = concat_path_file(path, chp);
  48. if (opts & 1) { /* -d */
  49. if (mkdtemp(chp) == NULL)
  50. return EXIT_FAILURE;
  51. } else {
  52. if (mkstemp(chp) < 0)
  53. return EXIT_FAILURE;
  54. }
  55. puts(chp);
  56. return EXIT_SUCCESS;
  57. }