|
1 | 1 | #include "common.hpp" |
2 | 2 | #include "defines.hpp" |
3 | | -#include <exception> |
| 3 | +#include <chrono> |
4 | 4 | #include <filesystem> |
5 | 5 | #include <fstream> |
6 | 6 | #include <iostream> |
| 7 | +#include <random> |
7 | 8 | #include <stdexcept> |
8 | 9 |
|
9 | | -bool create_tmp_dbc_with(const char* filename, const char* content) { |
10 | | - auto* file = std::fopen(filename, "w"); |
11 | | - if (!file) { |
12 | | - return false; |
13 | | - } |
| 10 | +// Don't want to use tmpnam due to warnings. So here is an alternative using time and random numbers. |
| 11 | +// This should be platform agnostic as well. |
| 12 | +static std::string generate_unique_filename(); |
| 13 | +std::string generate_unique_filename() { |
| 14 | + // Get current time since epoch |
| 15 | + auto now = std::chrono::system_clock::now(); |
| 16 | + auto duration = now.time_since_epoch(); |
| 17 | + auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(); |
| 18 | + |
| 19 | + // Generate a random number |
| 20 | + std::random_device rd; |
| 21 | + std::mt19937 gen(rd()); |
| 22 | + std::uniform_int_distribution<> dis(0, 9999); |
| 23 | + int random_num = dis(gen); |
14 | 24 |
|
15 | | - std::fputs(PRIMITIVE_DBC.c_str(), file); |
16 | | - std::fputs(content, file); |
17 | | - std::fclose(file); |
18 | | - return true; |
| 25 | + // Concatenate time and random number to create a unique filename |
| 26 | + return "temp_file_" + std::to_string(milliseconds) + "_" + std::to_string(random_num) + ".txt"; |
19 | 27 | } |
20 | 28 |
|
21 | 29 | std::string create_temporary_dbc_with(const char* contents) { |
22 | 30 | std::filesystem::path temp_dir = std::filesystem::temp_directory_path(); |
23 | 31 |
|
24 | 32 | // Generate a unique temporary file name |
25 | | - char filename[] = "temp_file_XXXXXX"; |
26 | | - if (std::tmpnam(filename) == nullptr) { |
27 | | - throw std::runtime_error("Failed to generate a unique temporary filename."); |
28 | | - } |
| 33 | + std::string filename = generate_unique_filename(); |
29 | 34 | std::filesystem::path temp_file = temp_dir / filename; |
30 | 35 |
|
31 | 36 | std::ofstream file(temp_file); |
|
0 commit comments