]> git.decadent.org.uk Git - videolink.git/blobdiff - temp_file.cpp
Replaced auto_temp_file with temp_file, which handles creation as well as deletion.
[videolink.git] / temp_file.cpp
diff --git a/temp_file.cpp b/temp_file.cpp
new file mode 100644 (file)
index 0000000..6b8165c
--- /dev/null
@@ -0,0 +1,53 @@
+// Copyright 2005 Ben Hutchings <ben@decadentplace.org.uk>.
+// See the file "COPYING" for licence details.
+
+#include "temp_file.hpp"
+
+#include <cassert>
+#include <cerrno>
+#include <cstdlib>
+#include <cstring>
+#include <stdexcept>
+#include <vector>
+
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <glibmm/fileutils.h>
+
+temp_file::temp_file(const std::string & base_name)
+{
+    fd_ = Glib::file_open_tmp(name_, base_name);
+    assert(fd_ >= 0);
+
+    // Workaround bug in glibc <2.2 that may cause the file to be
+    // created with lax permissions.
+#   ifdef __GLIBC__
+#   if !__GLIBC_PREREQ(2, 2)
+    if (fchmod(fd_, S_IREAD|S_IWRITE) != 0 || ftruncate(fd_, 0) != 0)
+    {
+       close(fd_);
+       throw std::runtime_error(std::strerror(errno));
+    }
+#   endif
+#   endif
+}
+
+temp_file::~temp_file()
+{
+    close();
+
+    // Don't assert that this is successful.  The file could have
+    // been removed by another process.
+    unlink(name_.c_str());
+}
+
+void temp_file::close()
+{
+    if (fd_ >= 0)
+    {
+       int result = ::close(fd_);
+       assert(result == 0);
+       fd_ = -1;
+    }
+}