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