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

#include <cstdio>

class TmpFile
{
public:
	TmpFile(const std::string& data = {})
	{
		auto tmp_dir = std::filesystem::temp_directory_path();
		auto tmp_file_template = tmp_dir / "ctor_tmp_file-";
		std::FILE* fp{nullptr};
		int counter{};
		while(!fp)
		{
			filename = tmp_file_template.string() + std::to_string(counter++);
			fp = std::fopen(filename.data(), "wx");
		}
		std::fwrite(data.data(), data.size(), 1, fp);
		std::fclose(fp);
	}

	~TmpFile()
	{
		std::filesystem::remove(filename);
	}

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

private:
	std::string filename;
};