Last active
November 18, 2023 12:24
-
-
Save jemand2001/36ef99fcf2974072e8892ebea5a543f5 to your computer and use it in GitHub Desktop.
an RAII wrapper around the c mktemp api (cleans up after itself)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <cstdlib> | |
| #include <unistd.h> | |
| #include <cerrno> | |
| #include <cstdio> | |
| #include <cstring> | |
| #include <fstream> | |
| #include <iostream> | |
| #include <stdexcept> | |
| #include <string> | |
| #include <filesystem> | |
| #include <thread> | |
| #include <chrono> | |
| class TempFile { | |
| std::string filename; | |
| public: | |
| TempFile(const std::string &s) : filename{s} { | |
| int tmpfd = ::mkstemp(filename.data()); | |
| if (tmpfd == -1) { | |
| throw std::ios::failure(std::strerror(errno)); | |
| } | |
| close(tmpfd); | |
| } | |
| std::fstream open(std::ios::openmode mode = std::ios::out) { | |
| return std::fstream(filename, mode); | |
| } | |
| ~TempFile() { | |
| if (!filename.empty() && std::filesystem::exists(filename)) { | |
| std::fstream lock(filename, std::ios::noreplace); | |
| std::filesystem::remove(filename); | |
| } | |
| } | |
| TempFile() = delete; | |
| TempFile(const TempFile&) = delete; | |
| auto operator=(const TempFile &) = delete; | |
| TempFile(TempFile &&other) : filename(std::move(other.filename)) {} | |
| TempFile &operator=(TempFile &&other) { | |
| if (this == &other) | |
| return *this; | |
| filename = std::move(other.filename); | |
| } | |
| }; | |
| int main() { | |
| using namespace std::chrono_literals; | |
| TempFile f("testXXXXXX"); | |
| auto stream = f.open(); | |
| stream << "Hello, World!\n"; | |
| stream.flush(); | |
| auto other = f.open(std::ios::in); | |
| std::string line; | |
| std::getline(other, line); | |
| std::cout << line; | |
| std::this_thread::sleep_for(20s); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment