diff options
author | Roland Reichwein <mail@reichwein.it> | 2023-01-02 16:32:01 +0100 |
---|---|---|
committer | Roland Reichwein <mail@reichwein.it> | 2023-01-02 16:32:01 +0100 |
commit | d00dc2c69164d8a8850d317f2868c6f131b7f679 (patch) | |
tree | c206c5088be0ed2fa0af692f1e0bc739f66d0b0a /tempfile.cpp |
First lib versionv1.0
Diffstat (limited to 'tempfile.cpp')
-rw-r--r-- | tempfile.cpp | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/tempfile.cpp b/tempfile.cpp new file mode 100644 index 0000000..f425db2 --- /dev/null +++ b/tempfile.cpp @@ -0,0 +1,42 @@ +#include "tempfile.h" + +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#include <iostream> + +namespace fs = std::filesystem; +using namespace std::string_literals; + +fs::path Tempfile::GetPath() const +{ + return m_path; +} + +Tempfile::Tempfile(const std::filesystem::path& extension) +{ + try { + fs::path path { fs::temp_directory_path() / "tempfileXXXXXX"}; + if (!extension.empty()) + path += extension; + + fs::path::string_type name{path.native()}; + int fd = mkstemps(name.data(), extension.native().size()); + if (fd == -1) + std::runtime_error("mkstemps: "s + strerror(errno)); + close(fd); + m_path = std::string{name}; + } catch (const std::exception& ex) { + throw std::runtime_error("Tempfile error: "s + ex.what()); + } +} + +Tempfile::~Tempfile() +{ + try { + fs::remove_all(m_path); + } catch (const std::exception& ex) { + std::cerr << "Warning: Couldn't remove temporary file " << m_path << std::endl; + } +} |