]> git.decadent.org.uk Git - videolink.git/blob - temp_file.cpp
Replaced auto_temp_file with temp_file, which handles creation as well as deletion.
[videolink.git] / temp_file.cpp
1 // Copyright 2005 Ben Hutchings <ben@decadentplace.org.uk>.
2 // See the file "COPYING" for licence details.
3
4 #include "temp_file.hpp"
5
6 #include <cassert>
7 #include <cerrno>
8 #include <cstdlib>
9 #include <cstring>
10 #include <stdexcept>
11 #include <vector>
12
13 #include <fcntl.h>
14 #include <unistd.h>
15
16 #include <glibmm/fileutils.h>
17
18 temp_file::temp_file(const std::string & base_name)
19 {
20     fd_ = Glib::file_open_tmp(name_, base_name);
21     assert(fd_ >= 0);
22
23     // Workaround bug in glibc <2.2 that may cause the file to be
24     // created with lax permissions.
25 #   ifdef __GLIBC__
26 #   if !__GLIBC_PREREQ(2, 2)
27     if (fchmod(fd_, S_IREAD|S_IWRITE) != 0 || ftruncate(fd_, 0) != 0)
28     {
29         close(fd_);
30         throw std::runtime_error(std::strerror(errno));
31     }
32 #   endif
33 #   endif
34 }
35
36 temp_file::~temp_file()
37 {
38     close();
39
40     // Don't assert that this is successful.  The file could have
41     // been removed by another process.
42     unlink(name_.c_str());
43 }
44
45 void temp_file::close()
46 {
47     if (fd_ >= 0)
48     {
49         int result = ::close(fd_);
50         assert(result == 0);
51         fd_ = -1;
52     }
53 }