]> git.decadent.org.uk Git - videolink.git/blob - temp_file.cpp
Added debugging option to keep temporary files.
[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     if (!keep_)
41     {
42         // Don't assert that this is successful.  The file could have
43         // been removed by another process.
44         unlink(name_.c_str());
45     }
46 }
47
48 void temp_file::close()
49 {
50     if (fd_ >= 0)
51     {
52         int result = ::close(fd_);
53         assert(result == 0);
54         fd_ = -1;
55     }
56 }
57
58 bool temp_file::keep_ = false;
59
60 void temp_file::keep_all(bool keep)
61 {
62     keep_ = keep;
63 }