]> git.lyx.org Git - lyx.git/blob - src/support/tempname.C
fix a couple of hard crashes, constify local variables, whitespace changes, some...
[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 "debug.h"
10
11 using std::endl;
12
13 extern string system_tempdir;
14
15 string const lyx::tempName(string const & dir, string const & mask)
16 {
17         string const tmpdir(dir.empty() ? system_tempdir : dir);
18         string tmpfl(AddName(tmpdir, mask));
19         tmpfl += tostr(getpid());
20         tmpfl += "XXXXXX";
21
22         // The supposedly safe mkstemp version
23         char * tmpl = new char[tmpfl.length() + 1]; // + 1 for '\0'
24         tmpfl.copy(tmpl, string::npos);
25         tmpl[tmpfl.length()] = '\0'; // terminator
26         
27         int const tmpf = ::mkstemp(tmpl);
28         if (tmpf != -1) {
29                 string const t(tmpl);
30                 ::close(tmpf);
31                 delete [] tmpl;
32                 lyxerr[Debug::FILES] << "Temporary file `" << t
33                                      << "' created." << endl;
34                 return t;
35         } else {
36                 lyxerr[Debug::FILES]
37                         << "LyX Error: Unable to create temporary file."
38                         << endl;
39                 delete [] tmpl;
40                 return string();
41         }
42 }