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