byteme
C++ wrappers for buffered inputs
Loading...
Searching...
No Matches
temp_file_path.hpp
Go to the documentation of this file.
1#ifndef BYTEME_TEMP_FILE_PATH_HPP
2#define BYTEME_TEMP_FILE_PATH_HPP
3
4#if __has_include(<filesystem>)
5#include <filesystem>
6namespace fs = std::filesystem;
7#else
8#include <experimental/filesystem>
9namespace fs = std::experimental::filesystem;
10#endif
11
12#include <random>
13#include <chrono>
14#include <string>
15#include <cstdint>
16#include <fstream>
17
24namespace byteme {
25
36inline std::string temp_file_path(const std::string& prefix, const std::string& ext) {
37 auto path = fs::temp_directory_path();
38 path.append(prefix);
39
40 // Hopefully, we create a new seed when the function re-runs.
41 uint64_t seed;
42 try {
43 std::random_device rd;
44 seed = rd();
45 } catch (...) {
46 auto now = std::chrono::system_clock::now();
47 seed = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
48 }
49
50 std::mt19937_64 rng(seed);
51 while (1) {
52 auto copy = path;
53 copy += std::to_string(rng());
54 copy += ext;
55
56 if (!fs::exists(copy)) {
57 path = std::move(copy);
58 break;
59 }
60 }
61
62 // Force the creation of the file. This is not entirely thread-safe
63 // as the existence check is done separately, but there's no way to
64 // guarantee safety without OS-level mechanics.
65 std::ofstream dummy(path, std::ofstream::out);
66 return path.string();
67}
68
74inline std::string temp_file_path(const std::string& prefix) {
75 return temp_file_path(prefix, "");
76}
77
78}
79
80#endif
Simple byte readers and writers.
std::string temp_file_path(const std::string &prefix, const std::string &ext)
Definition temp_file_path.hpp:36