mktemp.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "tempfile.h"
  2. #include <util/folder/dirut.h>
  3. #include <util/generic/yexception.h>
  4. #include <cstring>
  5. #ifdef _win32_
  6. #include "winint.h"
  7. #include <io.h>
  8. #else
  9. #include <unistd.h>
  10. #endif
  11. extern "C" int mkstemps(char* path, int slen);
  12. TString MakeTempName(const char* wrkDir, const char* prefix, const char* extension) {
  13. #ifndef _win32_
  14. TString filePath;
  15. if (wrkDir && *wrkDir) {
  16. filePath += wrkDir;
  17. } else {
  18. filePath += GetSystemTempDir();
  19. }
  20. if (filePath.back() != '/') {
  21. filePath += '/';
  22. }
  23. if (prefix) {
  24. filePath += prefix;
  25. }
  26. filePath += "XXXXXX"; // mkstemps requirement
  27. size_t extensionPartLength = 0;
  28. if (extension && *extension) {
  29. if (extension[0] != '.') {
  30. filePath += '.';
  31. extensionPartLength += 1;
  32. }
  33. filePath += extension;
  34. extensionPartLength += strlen(extension);
  35. }
  36. int fd = mkstemps(const_cast<char*>(filePath.data()), extensionPartLength);
  37. if (fd >= 0) {
  38. close(fd);
  39. return filePath;
  40. }
  41. #else
  42. char tmpDir[MAX_PATH + 1]; // +1 -- for terminating null character
  43. char filePath[MAX_PATH];
  44. const char* pDir = 0;
  45. if (wrkDir && *wrkDir) {
  46. pDir = wrkDir;
  47. } else if (GetTempPath(MAX_PATH + 1, tmpDir)) {
  48. pDir = tmpDir;
  49. }
  50. // it always takes up to 3 characters, no more
  51. if (GetTempFileName(pDir, (prefix) ? (prefix) : "yan", 0, filePath)) {
  52. return filePath;
  53. }
  54. #endif
  55. ythrow TSystemError() << "can not create temp name(" << wrkDir << ", " << prefix << ", " << extension << ")";
  56. }