diff --git a/src/create_file.cpp b/src/create_file.cpp index 4dde405..947263a 100644 --- a/src/create_file.cpp +++ b/src/create_file.cpp @@ -10,6 +10,10 @@ #include #include +#if __has_include() +#include +#endif + namespace tmp::detail { namespace fs = std::filesystem; @@ -18,11 +22,29 @@ namespace fs = std::filesystem; /// @returns A pointer to the file stream associated with the temporary file /// @throws fs::filesystem_error if cannot create a temporary file std::FILE* create_file() { +#if __has_include() + std::string path = fs::temp_directory_path() / "XXXXXX"; + int descriptor = mkstemp(path.data()); + if (descriptor == -1) { + std::error_code ec = std::error_code(errno, std::generic_category()); + throw fs::filesystem_error("Cannot create a temporary file", ec); + } + + unlink(path.data()); + + std::FILE* file = fdopen(descriptor, "wb+"); + if (file == nullptr) { + std::error_code ec = std::error_code(errno, std::generic_category()); + close(descriptor); + throw fs::filesystem_error("Cannot create a temporary file", ec); + } +#else std::FILE* file = std::tmpfile(); if (file == nullptr) { std::error_code ec = std::error_code(errno, std::generic_category()); throw fs::filesystem_error("Cannot create a temporary file", ec); } +#endif return file; }