tempfile.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (C) 2002 Jeff Dike (jdike@karaya.com)
  3. * Licensed under the GPL
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <string.h>
  9. #include <errno.h>
  10. #include <sys/param.h>
  11. #include "init.h"
  12. /* Modified from create_mem_file and start_debugger */
  13. static char *tempdir = NULL;
  14. static void __init find_tempdir(void)
  15. {
  16. char *dirs[] = { "TMP", "TEMP", "TMPDIR", NULL };
  17. int i;
  18. char *dir = NULL;
  19. if(tempdir != NULL) return; /* We've already been called */
  20. for(i = 0; dirs[i]; i++){
  21. dir = getenv(dirs[i]);
  22. if((dir != NULL) && (*dir != '\0'))
  23. break;
  24. }
  25. if((dir == NULL) || (*dir == '\0'))
  26. dir = "/tmp";
  27. tempdir = malloc(strlen(dir) + 2);
  28. if(tempdir == NULL){
  29. fprintf(stderr, "Failed to malloc tempdir, "
  30. "errno = %d\n", errno);
  31. return;
  32. }
  33. strcpy(tempdir, dir);
  34. strcat(tempdir, "/");
  35. }
  36. int make_tempfile(const char *template, char **out_tempname, int do_unlink)
  37. {
  38. char tempname[MAXPATHLEN];
  39. int fd;
  40. find_tempdir();
  41. if (*template != '/')
  42. strcpy(tempname, tempdir);
  43. else
  44. *tempname = 0;
  45. strcat(tempname, template);
  46. fd = mkstemp(tempname);
  47. if(fd < 0){
  48. fprintf(stderr, "open - cannot create %s: %s\n", tempname,
  49. strerror(errno));
  50. return -1;
  51. }
  52. if(do_unlink && (unlink(tempname) < 0)){
  53. perror("unlink");
  54. return -1;
  55. }
  56. if(out_tempname){
  57. *out_tempname = strdup(tempname);
  58. if(*out_tempname == NULL){
  59. perror("strdup");
  60. return -1;
  61. }
  62. }
  63. return(fd);
  64. }
  65. /*
  66. * Overrides for Emacs so that we follow Linus's tabbing style.
  67. * Emacs will notice this stuff at the end of the file and automatically
  68. * adjust the settings for this buffer only. This must remain at the end
  69. * of the file.
  70. * ---------------------------------------------------------------------------
  71. * Local variables:
  72. * c-file-style: "linux"
  73. * End:
  74. */