Skip to content

Commit a70fc65

Browse files
committed
Remove the old temporary file function and removing the last instance of tmpnam with a time / random generator solution
1 parent f2dc698 commit a70fc65

2 files changed

Lines changed: 19 additions & 15 deletions

File tree

test/common.cpp

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,36 @@
11
#include "common.hpp"
22
#include "defines.hpp"
3-
#include <exception>
3+
#include <chrono>
44
#include <filesystem>
55
#include <fstream>
66
#include <iostream>
7+
#include <random>
78
#include <stdexcept>
89

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);
1424

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";
1927
}
2028

2129
std::string create_temporary_dbc_with(const char* contents) {
2230
std::filesystem::path temp_dir = std::filesystem::temp_directory_path();
2331

2432
// 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();
2934
std::filesystem::path temp_file = temp_dir / filename;
3035

3136
std::ofstream file(temp_file);

test/common.hpp

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
#include <string>
55

6-
bool create_tmp_dbc_with(const char* filename, const char* content);
76
std::string create_temporary_dbc_with(const char* contents);
87

98
#endif // COMMON_H

0 commit comments

Comments
 (0)