summaryrefslogtreecommitdiff
path: root/test/tmpfile.h
blob: 5d114d07de8902059e09825c4cd23ba462429f28 (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
// -*- c++ -*-
// Distributed under the BSD 2-Clause License.
// See accompanying file LICENSE for details.
#pragma once

#include <cstdlib>
#include <unistd.h>

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif

struct tmp_file
{
	tmp_file(const std::string& data = {})
	{
		int fd;
#ifdef _WIN32
		char templ[] = "ctor_tmp_file-XXXXXX"; // buffer for filename
		_mktemp_s(templ, sizeof(templ));
		fd = open(templ, O_CREAT | O_RDWR);
#else
		char templ[] = "/tmp/ctor_tmp_file-XXXXXX"; // buffer for filename
		fd = mkstemp(templ);
#endif
		filename = templ;
		auto sz = write(fd, data.data(), data.size());
		(void)sz;
		close(fd);
	}

	~tmp_file()
	{
		unlink(filename.data());
	}

	const std::string& get() const
	{
		return filename;
	}

private:
	std::string filename;
};