mktemp.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2018 K. Lange
  5. *
  6. * mktemp - create a temporary directory and print its name
  7. */
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <getopt.h>
  12. #include <unistd.h>
  13. #include <errno.h>
  14. #include <sys/stat.h>
  15. int main(int argc, char * argv[]) {
  16. int opt;
  17. int dry_run = 0;
  18. int quiet = 0;
  19. int directory = 0;
  20. while ((opt = getopt(argc,argv,"duq")) != -1) {
  21. switch (opt) {
  22. case 'd':
  23. directory = 1;
  24. break;
  25. case 'u':
  26. dry_run = 1;
  27. break;
  28. case 'q':
  29. quiet = 1;
  30. break;
  31. }
  32. }
  33. char * template;
  34. int i = optind;
  35. if (i == argc) {
  36. template = strdup("/tmp/tmp.XXXXXX");
  37. } else {
  38. template = strdup(argv[i]);
  39. }
  40. char * result = mktemp(template);
  41. if (!result) {
  42. fprintf(stderr, "%s: %s\n", argv[0], strerror(errno));
  43. return 1;
  44. }
  45. if (!quiet) {
  46. fprintf(stdout, "%s\n", result);
  47. }
  48. if (!dry_run) {
  49. if (directory) {
  50. if (mkdir(result,0777) < 0) {
  51. fprintf(stderr, "%s: mkdir: %s: %s\n", argv[0], result, strerror(errno));
  52. return 1;
  53. }
  54. } else {
  55. FILE * f = fopen(result,"w");
  56. if (!f) {
  57. fprintf(stderr, "%s: open: %s: %s\n", argv[0], result, strerror(errno));
  58. return 1;
  59. }
  60. }
  61. }
  62. return 0;
  63. }