mktemp.c 526 B

123456789101112131415161718192021222324252627282930313233
  1. #include <stdlib.h>
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6. #include <stdio.h>
  7. char*
  8. mktemp(char *template)
  9. {
  10. int n;
  11. long x;
  12. char *p;
  13. int c;
  14. struct stat stbuf;
  15. n = strlen(template);
  16. p = template+n-6;
  17. if (n < 6 || strcmp(p, "XXXXXX") != 0) {
  18. *template = 0;
  19. } else {
  20. x = getpid() % 100000;
  21. sprintf(p, "%05d", x);
  22. p += 5;
  23. for(c = 'a'; c <= 'z'; c++) {
  24. *p = c;
  25. if (stat(template, &stbuf) < 0)
  26. return template;
  27. }
  28. *template = 0;
  29. }
  30. return template;
  31. }