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>
Comment on lines 10 to 11

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
#include <filesystem>
#include <system_error>
#include <filesystem>
#include <string>
#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());

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On Linux O_TMPFILE is availible, we should use it and fall back to mkstemp on other POSIX systems

if (descriptor == -1) {
std::error_code ec = std::error_code(errno, std::generic_category());

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
std::error_code ec = std::error_code(errno, std::generic_category());
std::error_code ec = std::error_code(errno, std::system_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());

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
std::error_code ec = std::error_code(errno, std::generic_category());
std::error_code ec = std::error_code(errno, std::system_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