mkdtemp.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (c) 2017 Colin Watson <cjwatson@debian.org>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. /* Roughly equivalent to "mktemp -d -t TEMPLATE", but portable. */
  17. #include "includes.h"
  18. #include <limits.h>
  19. #include <stdarg.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <unistd.h>
  23. #include "log.h"
  24. static void
  25. usage(void)
  26. {
  27. fprintf(stderr, "mkdtemp template\n");
  28. exit(1);
  29. }
  30. int
  31. main(int argc, char **argv)
  32. {
  33. const char *base;
  34. const char *tmpdir;
  35. char template[PATH_MAX];
  36. int r;
  37. char *dir;
  38. if (argc != 2)
  39. usage();
  40. base = argv[1];
  41. if ((tmpdir = getenv("TMPDIR")) == NULL)
  42. tmpdir = "/tmp";
  43. r = snprintf(template, sizeof(template), "%s/%s", tmpdir, base);
  44. if (r < 0 || (size_t)r >= sizeof(template))
  45. fatal("template string too long");
  46. dir = mkdtemp(template);
  47. if (dir == NULL) {
  48. perror("mkdtemp");
  49. exit(1);
  50. }
  51. puts(dir);
  52. return 0;
  53. }