]> git.lyx.org Git - lyx.git/blob - src/support/tempname.C
Conditionally #include headers.
[lyx.git] / src / support / tempname.C
1 /**
2  * \file tempname.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "support/lyxlib.h"
14 #include "support/filetools.h"
15 #include "support/tostr.h"
16 #include "support/os.h"
17
18 #include "debug.h"
19
20 #include <boost/scoped_array.hpp>
21
22 #include <cstdlib>
23 #include <unistd.h>
24
25 #if !defined(HAVE_MKSTEMP) && defined(HAVE_MKTEMP)
26 # include <fcntl.h>
27 # include <sys/stat.h>
28 #endif
29
30 using boost::scoped_array;
31
32 using std::string;
33 using std::endl;
34
35 namespace {
36
37 inline
38 int make_tempfile(char * templ)
39 {
40 #if defined(HAVE_MKSTEMP)
41         return ::mkstemp(templ);
42 #elif defined(HAVE_MKTEMP)
43         // This probably just barely works...
44         ::mktemp(templ);
45         return ::open(templ, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
46 #else
47 #error FIX FIX FIX
48 #endif
49 }
50
51 } // namespace anon
52
53
54 string const lyx::support::tempName(string const & dir, string const & mask)
55 {
56         string const tmpdir(dir.empty() ? os::getTmpDir() : dir);
57         string tmpfl(AddName(tmpdir, mask));
58         tmpfl += tostr(getpid());
59         tmpfl += "XXXXXX";
60
61         // The supposedly safe mkstemp version
62         scoped_array<char> tmpl(new char[tmpfl.length() + 1]); // + 1 for '\0'
63         tmpfl.copy(tmpl.get(), string::npos);
64         tmpl[tmpfl.length()] = '\0'; // terminator
65
66         int const tmpf = make_tempfile(tmpl.get());
67         if (tmpf != -1) {
68                 string const t(tmpl.get());
69                 ::close(tmpf);
70                 lyxerr[Debug::FILES] << "Temporary file `" << t
71                                      << "' created." << endl;
72                 return t;
73         } else {
74                 lyxerr[Debug::FILES]
75                         << "LyX Error: Unable to create temporary file."
76                         << endl;
77                 return string();
78         }
79 }