tmpnam.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. @deftypefn Supplemental char* tmpnam (char *@var{s})
  3. This function attempts to create a name for a temporary file, which
  4. will be a valid file name yet not exist when @code{tmpnam} checks for
  5. it. @var{s} must point to a buffer of at least @code{L_tmpnam} bytes,
  6. or be @code{NULL}. Use of this function creates a security risk, and it must
  7. not be used in new projects. Use @code{mkstemp} instead.
  8. @end deftypefn
  9. */
  10. #include <stdio.h>
  11. #ifndef L_tmpnam
  12. #define L_tmpnam 100
  13. #endif
  14. #ifndef P_tmpdir
  15. #define P_tmpdir "/usr/tmp"
  16. #endif
  17. static char tmpnam_buffer[L_tmpnam];
  18. static int tmpnam_counter;
  19. extern int getpid (void);
  20. char *
  21. tmpnam (char *s)
  22. {
  23. int pid = getpid ();
  24. if (s == NULL)
  25. s = tmpnam_buffer;
  26. /* Generate the filename and make sure that there isn't one called
  27. it already. */
  28. while (1)
  29. {
  30. FILE *f;
  31. sprintf (s, "%s/%s%x.%x", P_tmpdir, "t", pid, tmpnam_counter);
  32. f = fopen (s, "r");
  33. if (f == NULL)
  34. break;
  35. tmpnam_counter++;
  36. fclose (f);
  37. }
  38. return s;
  39. }