blob: a5d40436588a0e34e206c9e404249a20ff4a75e2 (
plain)
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
|
// -*- c++ -*-
// Distributed under the BSD 2-Clause License.
// See accompanying file LICENSE for details.
#pragma once
#include <cstdlib>
#include <cstring>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <io.h>
#else
#include <unistd.h>
#endif
struct tmp_file
{
tmp_file(const std::string& data = {})
{
int fd;
auto tmp_dir = std::filesystem::temp_directory_path();
auto tmp_file_template = tmp_dir / "ctor_tmp_file-XXXXXX";
filename = tmp_file_template.string();
auto buf = new char[filename.size() + 2];
memcpy(buf, filename.data(), filename.size() + 1);
#ifdef _WIN32
_mktemp_s(buf, filename.size() + 2);
filename = buf;
fd = _open(filename.data(), O_CREAT | O_RDWR, _S_IWRITE);
auto sz = _write(fd, data.data(), data.size());
(void)sz;
_close(fd);
#else
fd = mkstemp(buf);
filename = buf;
auto sz = write(fd, data.data(), data.size());
(void)sz;
close(fd);
#endif
delete[] buf;
}
~tmp_file()
{
#ifdef _WIN32
_unlink(filename.data());
#else
unlink(filename.data());
#endif
}
const std::string& get() const
{
return filename;
}
private:
std::string filename;
};
|