Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/create_file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
#include <filesystem>
#include <system_error>

#if __has_include(<unistd.h>)
#include <unistd.h>
#endif

namespace tmp::detail {

namespace fs = std::filesystem;
Expand All @@ -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(<unistd.h>)
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;
}
Expand Down
Loading