aboutsummaryrefslogtreecommitdiffstats
path: root/util/system/mktemp.cpp
blob: f0c1db8885c7018a81c1c4090266458acd4734ae (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include "tempfile.h"

#include <util/folder/dirut.h>
#include <util/generic/yexception.h>
#include <util/stream/file.h>

#include <cerrno>
#include <cstring>

#ifdef _win32_
    #include "winint.h"
    #include <io.h>
#else
    #include <unistd.h>
    #include <stdlib.h>
#endif
 
extern "C" int mkstemps(char* path, int slen);

TString MakeTempName(const char* wrkDir, const char* prefix, const char* extension) {
#ifndef _win32_
    TString filePath;

    if (wrkDir && *wrkDir) {
        filePath += wrkDir;
    } else {
        filePath += GetSystemTempDir();
    }

    if (filePath.back() != '/') {
        filePath += '/';
    }

    if (prefix) {
        filePath += prefix;
    }

    filePath += "XXXXXX"; // mkstemps requirement

    size_t extensionPartLength = 0;
    if (extension && *extension) {
        if (extension[0] != '.') {
            filePath += '.';
            extensionPartLength += 1;
        }
        filePath += extension;
        extensionPartLength += strlen(extension);
    }

    int fd = mkstemps(const_cast<char*>(filePath.data()), extensionPartLength);
    if (fd >= 0) {
        close(fd);
        return filePath;
    }
#else
    char tmpDir[MAX_PATH + 1]; // +1 -- for terminating null character
    char filePath[MAX_PATH];
    const char* pDir = 0;

    if (wrkDir && *wrkDir) {
        pDir = wrkDir;
    } else if (GetTempPath(MAX_PATH + 1, tmpDir)) {
        pDir = tmpDir;
    }

    // it always takes up to 3 characters, no more
    if (GetTempFileName(pDir, (prefix) ? (prefix) : "yan", 0, filePath)) {
        return filePath;
    }
#endif

    ythrow TSystemError() << "can not create temp name(" << wrkDir << ", " << prefix << ", " << extension << ")";
}