Skip to content

Instantly share code, notes, and snippets.

@jemand2001
Last active November 18, 2023 12:24
Show Gist options
  • Select an option

  • Save jemand2001/36ef99fcf2974072e8892ebea5a543f5 to your computer and use it in GitHub Desktop.

Select an option

Save jemand2001/36ef99fcf2974072e8892ebea5a543f5 to your computer and use it in GitHub Desktop.
an RAII wrapper around the c mktemp api (cleans up after itself)
#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