From 8a40f5f49d428bbc89f54144d893a9fa16e3156c Mon Sep 17 00:00:00 2001 From: Bent Bisballe Nyeng Date: Fri, 21 Feb 2025 21:41:03 +0100 Subject: Clean up TmpFile class --- test/execute_test.cc | 2 +- test/tmpfile.h | 44 +++++++++++++++++--------------------------- 2 files changed, 18 insertions(+), 28 deletions(-) diff --git a/test/execute_test.cc b/test/execute_test.cc index 722b6ea..11b067f 100644 --- a/test/execute_test.cc +++ b/test/execute_test.cc @@ -53,7 +53,7 @@ public: auto cmd = locate("testprog", paths); uASSERT(!cmd.empty()); - tmp_file tmp; + TmpFile tmp; std::map env; diff --git a/test/tmpfile.h b/test/tmpfile.h index 5d114d0..0f83a20 100644 --- a/test/tmpfile.h +++ b/test/tmpfile.h @@ -3,39 +3,29 @@ // See accompanying file LICENSE for details. #pragma once -#include -#include +#include -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN -#include -#include -#include -#include -#endif - -struct tmp_file +class TmpFile { - tmp_file(const std::string& data = {}) +public: + TmpFile(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); + 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); } - ~tmp_file() + ~TmpFile() { - unlink(filename.data()); + std::filesystem::remove(filename); } const std::string& get() const -- cgit v1.2.3