]> git.lyx.org Git - lyx.git/blob - src/support/tempname.C
8c6480bdbcf2b9830a59c5b0f32090ff8604a0ed
[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 using boost::scoped_array;
26
27 using std::string;
28 using std::endl;
29
30 namespace {
31
32 inline
33 int make_tempfile(char * templ)
34 {
35 #if defined(HAVE_MKSTEMP)
36         return ::mkstemp(templ);
37 #elif defined(HAVE_MKTEMP)
38         // This probably just barely works...
39         ::mktemp(templ);
40         return ::open(templ, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
41 #else
42 #error FIX FIX FIX
43 #endif
44 }
45
46 } // namespace anon
47
48
49 string const lyx::support::tempName(string const & dir, string const & mask)
50 {
51         string const tmpdir(dir.empty() ? os::getTmpDir() : dir);
52         string tmpfl(AddName(tmpdir, mask));
53         tmpfl += tostr(getpid());
54         tmpfl += "XXXXXX";
55
56         // The supposedly safe mkstemp version
57         scoped_array<char> tmpl(new char[tmpfl.length() + 1]); // + 1 for '\0'
58         tmpfl.copy(tmpl.get(), string::npos);
59         tmpl[tmpfl.length()] = '\0'; // terminator
60
61         int const tmpf = make_tempfile(tmpl.get());
62         if (tmpf != -1) {
63                 string const t(tmpl.get());
64                 ::close(tmpf);
65                 lyxerr[Debug::FILES] << "Temporary file `" << t
66                                      << "' created." << endl;
67                 return t;
68         } else {
69                 lyxerr[Debug::FILES]
70                         << "LyX Error: Unable to create temporary file."
71                         << endl;
72                 return string();
73         }
74 }