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